diff --git a/pkg/assets/link.go b/pkg/assets/link.go index 8e93389cda..3d5158564d 100644 --- a/pkg/assets/link.go +++ b/pkg/assets/link.go @@ -98,7 +98,7 @@ var linkFmtThreshold = (*Link)(new(big.Int).Exp(big.NewInt(10), big.NewInt(12), // MarshalText implements the encoding.TextMarshaler interface. func (l *Link) MarshalText() ([]byte, error) { if l.Cmp(linkFmtThreshold) >= 0 { - return []byte(fmt.Sprintf("%s link", decimal.NewFromBigInt(l.ToInt(), -18))), nil + return fmt.Appendf(nil, "%s link", decimal.NewFromBigInt(l.ToInt(), -18)), nil } return (*big.Int)(l).MarshalText() } @@ -109,7 +109,7 @@ func (l Link) MarshalJSON() ([]byte, error) { if err != nil { return nil, err } - return []byte(fmt.Sprintf(`"%s"`, value)), nil + return fmt.Appendf(nil, `"%s"`, value), nil } // UnmarshalJSON implements the json.Unmarshaler interface. @@ -166,7 +166,7 @@ func (l Link) Value() (driver.Value, error) { } // Scan reads the database value and returns an instance. -func (l *Link) Scan(value interface{}) error { +func (l *Link) Scan(value any) error { switch v := value.(type) { case string: decoded, ok := l.SetString(v, 10) diff --git a/pkg/beholder/chip_ingress_emitter.go b/pkg/beholder/chip_ingress_emitter.go index f5724c1cb9..ea412c8780 100644 --- a/pkg/beholder/chip_ingress_emitter.go +++ b/pkg/beholder/chip_ingress_emitter.go @@ -3,6 +3,7 @@ package beholder import ( "context" "fmt" + "maps" "github.com/smartcontractkit/chainlink-common/pkg/chipingress" ) @@ -83,9 +84,7 @@ func ExtractAttributes(attrKVs ...any) map[string]any { attributes := newAttributes(attrKVs...) attributesMap := make(map[string]any) - for key, value := range attributes { - attributesMap[key] = value - } + maps.Copy(attributesMap, attributes) return attributesMap } diff --git a/pkg/beholder/message.go b/pkg/beholder/message.go index 52a2c02b4b..fb3eee76c7 100644 --- a/pkg/beholder/message.go +++ b/pkg/beholder/message.go @@ -3,6 +3,7 @@ package beholder import ( "errors" "fmt" + "maps" "regexp" "strings" @@ -80,9 +81,7 @@ func newAttributes(attrKVs ...any) Attributes { for i := 0; i < l; { switch t := attrKVs[i].(type) { case Attributes: - for k, v := range t { - a[k] = v - } + maps.Copy(a, t) i++ case string: if i+1 >= l { @@ -111,9 +110,7 @@ func (e *Message) AddAttributes(attrKVs ...any) { if e.Attrs == nil { e.Attrs = make(map[string]any, len(attrs)/2) } - for k, v := range attrs { - e.Attrs[k] = v - } + maps.Copy(e.Attrs, attrs) } func (e *Message) OtelRecord() otellog.Record { @@ -122,9 +119,7 @@ func (e *Message) OtelRecord() otellog.Record { func (e *Message) Copy() Message { attrs := make(Attributes, len(e.Attrs)) - for k, v := range e.Attrs { - attrs[k] = v - } + maps.Copy(attrs, e.Attrs) c := Message{ Attrs: attrs, } diff --git a/pkg/capabilities/capabilities_test.go b/pkg/capabilities/capabilities_test.go index 0d2dc9534d..efb40df395 100644 --- a/pkg/capabilities/capabilities_test.go +++ b/pkg/capabilities/capabilities_test.go @@ -250,7 +250,7 @@ func TestOCRTriggerEvent_ToMapFromMap(t *testing.T) { // Test error handling t.Run("invalid map missing key", func(t *testing.T) { - invalidMap, err := values.NewMap(map[string]interface{}{ + invalidMap, err := values.NewMap(map[string]any{ "WrongKey": "value", }) require.NoError(t, err) diff --git a/pkg/capabilities/cli/cmd/generate-user-types/main.go b/pkg/capabilities/cli/cmd/generate-user-types/main.go index 49e1ea0ea4..e75ec5b1a9 100644 --- a/pkg/capabilities/cli/cmd/generate-user-types/main.go +++ b/pkg/capabilities/cli/cmd/generate-user-types/main.go @@ -76,7 +76,7 @@ func genForStruct() func(string) bool { func buildSkipGen() map[string]bool { skipGen := map[string]bool{} - for _, skip := range strings.Split(*skipCap, ",") { + for skip := range strings.SplitSeq(*skipCap, ",") { skipGen[skip] = true } return skipGen @@ -86,7 +86,7 @@ func buildGenPkgType() func(string) bool { genPkgType := func(_ string) bool { return true } if *types != "" { genPkg := map[string]bool{} - for _, t := range strings.Split(*types, ",") { + for t := range strings.SplitSeq(*types, ",") { genPkg[t] = true } genPkgType = func(s string) bool { diff --git a/pkg/capabilities/cli/cmd/generate_user_types.go b/pkg/capabilities/cli/cmd/generate_user_types.go index 47a1ba0a77..dfaafe4a5a 100644 --- a/pkg/capabilities/cli/cmd/generate_user_types.go +++ b/pkg/capabilities/cli/cmd/generate_user_types.go @@ -2,6 +2,7 @@ package cmd import ( "errors" + "maps" "os" "path" "strings" @@ -43,9 +44,7 @@ func GenerateUserTypes(info UserGenerationInfo) error { if i == 0 { generatedInfo = fileGeneratedInfo } else { - for name, strct := range fileGeneratedInfo.Types { - generatedInfo.Types[name] = strct - } + maps.Copy(generatedInfo.Types, fileGeneratedInfo.Types) } } diff --git a/pkg/capabilities/consensus/ocr3/aggregators/reduce_aggregator.go b/pkg/capabilities/consensus/ocr3/aggregators/reduce_aggregator.go index ddcfd5a26a..f63df075a4 100644 --- a/pkg/capabilities/consensus/ocr3/aggregators/reduce_aggregator.go +++ b/pkg/capabilities/consensus/ocr3/aggregators/reduce_aggregator.go @@ -7,6 +7,7 @@ import ( "fmt" "math" "math/big" + "slices" "sort" "strconv" "time" @@ -229,7 +230,7 @@ func (a *reduceAggregator) shouldReport(lggr logger.Logger, field AggregationFie if !bytes.Equal(v, unwrappedSingleValue.([]byte)) { return true, nil } - case map[string]interface{}, []any: + case map[string]any, []any: marshalledOldValue, err := proto.MarshalOptions{Deterministic: true}.Marshal(values.Proto(oldValue)) if err != nil { return false, err @@ -545,12 +546,7 @@ func formatReport(report map[string]any, format string) (any, error) { } func isOneOf(toCheck string, options []string) bool { - for _, option := range options { - if toCheck == option { - return true - } - } - return false + return slices.Contains(options, toCheck) } func NewReduceAggregator(config values.Map) (types.Aggregator, error) { diff --git a/pkg/capabilities/consensus/ocr3/aggregators/reduce_test.go b/pkg/capabilities/consensus/ocr3/aggregators/reduce_test.go index 16ed166b25..b48e60c36e 100644 --- a/pkg/capabilities/consensus/ocr3/aggregators/reduce_test.go +++ b/pkg/capabilities/consensus/ocr3/aggregators/reduce_test.go @@ -1,6 +1,7 @@ package aggregators_test import ( + "maps" "math/big" "testing" "time" @@ -1344,13 +1345,13 @@ func TestAggregateShouldReport(t *testing.T) { fields []aggregators.AggregationField mockValueFirstRound *values.Map shouldReportFirstRound bool - stateFirstRound map[string]interface{} + stateFirstRound map[string]any mockValueSecondRound *values.Map shouldReportSecondRound bool - stateSecondRound map[string]interface{} + stateSecondRound map[string]any mockValueThirdRound *values.Map shouldReportThirdRound bool - stateThirdRound map[string]interface{} + stateThirdRound map[string]any }{ { name: "OK-report_only_when_deviation_exceeded", @@ -1371,7 +1372,7 @@ func TestAggregateShouldReport(t *testing.T) { return mockValue }(), shouldReportFirstRound: true, - stateFirstRound: map[string]interface{}{"Time": decimal.NewFromInt(10)}, + stateFirstRound: map[string]any{"Time": decimal.NewFromInt(10)}, mockValueSecondRound: func() *values.Map { mockValue, err := values.WrapMap(map[string]any{ @@ -1382,7 +1383,7 @@ func TestAggregateShouldReport(t *testing.T) { }(), shouldReportSecondRound: false, // the delta between 10 and 30 is 20, which is less than the deviation of 30, so the state should remain the same - stateSecondRound: map[string]interface{}(map[string]interface{}{"Time": decimal.NewFromInt(10)}), + stateSecondRound: map[string]any(map[string]any{"Time": decimal.NewFromInt(10)}), mockValueThirdRound: func() *values.Map { mockValue, err := values.WrapMap(map[string]any{ @@ -1393,7 +1394,7 @@ func TestAggregateShouldReport(t *testing.T) { }(), shouldReportThirdRound: true, // the delta between 10 and 45 is 35, which is more than the deviation of 30, thats why the state is updated - stateThirdRound: map[string]interface{}{"Time": decimal.NewFromInt(45)}, + stateThirdRound: map[string]any{"Time": decimal.NewFromInt(45)}, }, { name: "NOK-do_not_report_if_deviation_type_any_byte_field_does_not_change", @@ -1422,7 +1423,7 @@ func TestAggregateShouldReport(t *testing.T) { return mockValue }(), shouldReportFirstRound: true, - stateFirstRound: map[string]interface{}(map[string]interface{}{ + stateFirstRound: map[string]any(map[string]any{ "FeedID": idABytes[:], "Time": decimal.NewFromInt(10), }), @@ -1436,7 +1437,7 @@ func TestAggregateShouldReport(t *testing.T) { return mockValue }(), shouldReportSecondRound: false, - stateSecondRound: map[string]interface{}(map[string]interface{}{ + stateSecondRound: map[string]any(map[string]any{ "FeedID": idABytes[:], "Time": decimal.NewFromInt(10), }), @@ -1468,7 +1469,7 @@ func TestAggregateShouldReport(t *testing.T) { return mockValue }(), shouldReportFirstRound: true, - stateFirstRound: map[string]interface{}{ + stateFirstRound: map[string]any{ "BoolField": true, "Time": decimal.NewFromInt(10), }, @@ -1482,7 +1483,7 @@ func TestAggregateShouldReport(t *testing.T) { return mockValue }(), shouldReportSecondRound: false, - stateSecondRound: map[string]interface{}(map[string]interface{}{ + stateSecondRound: map[string]any(map[string]any{ "BoolField": true, "Time": decimal.NewFromInt(10), }), @@ -1514,7 +1515,7 @@ func TestAggregateShouldReport(t *testing.T) { return mockValue }(), shouldReportFirstRound: true, - stateFirstRound: map[string]interface{}{ + stateFirstRound: map[string]any{ "FeedID": idABytes[:], "Time": decimal.NewFromInt(10), }, @@ -1528,7 +1529,7 @@ func TestAggregateShouldReport(t *testing.T) { return mockValue }(), shouldReportSecondRound: true, - stateSecondRound: map[string]interface{}(map[string]interface{}{ + stateSecondRound: map[string]any(map[string]any{ "FeedID": idBBytes[:], "Time": decimal.NewFromInt(10), }), @@ -1560,7 +1561,7 @@ func TestAggregateShouldReport(t *testing.T) { return mockValue }(), shouldReportFirstRound: true, - stateFirstRound: map[string]interface{}{ + stateFirstRound: map[string]any{ "BoolField": true, "Time": decimal.NewFromInt(10), }, @@ -1574,7 +1575,7 @@ func TestAggregateShouldReport(t *testing.T) { return mockValue }(), shouldReportSecondRound: true, - stateSecondRound: map[string]interface{}(map[string]interface{}{ + stateSecondRound: map[string]any(map[string]any{ "BoolField": false, "Time": decimal.NewFromInt(10), }), @@ -1606,7 +1607,7 @@ func TestAggregateShouldReport(t *testing.T) { return mockValue }(), shouldReportFirstRound: true, - stateFirstRound: map[string]interface{}{ + stateFirstRound: map[string]any{ "FeedID": "A", "Time": decimal.NewFromInt(10), }, @@ -1620,7 +1621,7 @@ func TestAggregateShouldReport(t *testing.T) { return mockValue }(), shouldReportSecondRound: true, - stateSecondRound: map[string]interface{}(map[string]interface{}{ + stateSecondRound: map[string]any(map[string]any{ "FeedID": "B", "Time": decimal.NewFromInt(10), }), @@ -1652,7 +1653,7 @@ func TestAggregateShouldReport(t *testing.T) { return mockValue }(), shouldReportFirstRound: true, - stateFirstRound: map[string]interface{}{ + stateFirstRound: map[string]any{ "FeedID": "A", "Time": decimal.NewFromInt(10), }, @@ -1666,7 +1667,7 @@ func TestAggregateShouldReport(t *testing.T) { return mockValue }(), shouldReportSecondRound: false, - stateSecondRound: map[string]interface{}(map[string]interface{}{ + stateSecondRound: map[string]any(map[string]any{ "FeedID": "A", "Time": decimal.NewFromInt(10), }), @@ -1698,7 +1699,7 @@ func TestAggregateShouldReport(t *testing.T) { return mockValue }(), shouldReportFirstRound: true, - stateFirstRound: map[string]interface{}{ + stateFirstRound: map[string]any{ "FeedID": map[string]any{"A": "A"}, "Time": decimal.NewFromInt(10), }, @@ -1712,7 +1713,7 @@ func TestAggregateShouldReport(t *testing.T) { return mockValue }(), shouldReportSecondRound: true, - stateSecondRound: map[string]interface{}(map[string]interface{}{ + stateSecondRound: map[string]any(map[string]any{ "FeedID": map[string]any{"A": "B"}, "Time": decimal.NewFromInt(10), }), @@ -1744,7 +1745,7 @@ func TestAggregateShouldReport(t *testing.T) { return mockValue }(), shouldReportFirstRound: true, - stateFirstRound: map[string]interface{}{ + stateFirstRound: map[string]any{ "FeedID": map[string]any{"A": "A"}, "Time": decimal.NewFromInt(10), }, @@ -1758,7 +1759,7 @@ func TestAggregateShouldReport(t *testing.T) { return mockValue }(), shouldReportSecondRound: false, - stateSecondRound: map[string]interface{}(map[string]interface{}{ + stateSecondRound: map[string]any(map[string]any{ "FeedID": map[string]any{"A": "A"}, "Time": decimal.NewFromInt(10), }), @@ -1790,7 +1791,7 @@ func TestAggregateShouldReport(t *testing.T) { return mockValue }(), shouldReportFirstRound: true, - stateFirstRound: map[string]interface{}{ + stateFirstRound: map[string]any{ "FeedID": []any{"A"}, "Time": decimal.NewFromInt(10), }, @@ -1804,7 +1805,7 @@ func TestAggregateShouldReport(t *testing.T) { return mockValue }(), shouldReportSecondRound: true, - stateSecondRound: map[string]interface{}(map[string]interface{}{ + stateSecondRound: map[string]any(map[string]any{ "FeedID": []any{"B"}, "Time": decimal.NewFromInt(10), }), @@ -1836,7 +1837,7 @@ func TestAggregateShouldReport(t *testing.T) { return mockValue }(), shouldReportFirstRound: true, - stateFirstRound: map[string]interface{}{ + stateFirstRound: map[string]any{ "FeedID": []any{"A"}, "Time": decimal.NewFromInt(10), }, @@ -1850,7 +1851,7 @@ func TestAggregateShouldReport(t *testing.T) { return mockValue }(), shouldReportSecondRound: false, - stateSecondRound: map[string]interface{}(map[string]interface{}{ + stateSecondRound: map[string]any(map[string]any{ "FeedID": []any{"A"}, "Time": decimal.NewFromInt(10), }), @@ -1882,7 +1883,7 @@ func TestAggregateShouldReport(t *testing.T) { return mockValue }(), shouldReportFirstRound: true, - stateFirstRound: map[string]interface{}{ + stateFirstRound: map[string]any{ "FeedID": int64(1), "Time": decimal.NewFromInt(10), }, @@ -1896,7 +1897,7 @@ func TestAggregateShouldReport(t *testing.T) { return mockValue }(), shouldReportSecondRound: true, - stateSecondRound: map[string]interface{}(map[string]interface{}{ + stateSecondRound: map[string]any(map[string]any{ "FeedID": int64(2), "Time": decimal.NewFromInt(10), }), @@ -1928,7 +1929,7 @@ func TestAggregateShouldReport(t *testing.T) { return mockValue }(), shouldReportFirstRound: true, - stateFirstRound: map[string]interface{}{ + stateFirstRound: map[string]any{ "FeedID": int64(1), "Time": decimal.NewFromInt(10), }, @@ -1942,7 +1943,7 @@ func TestAggregateShouldReport(t *testing.T) { return mockValue }(), shouldReportSecondRound: false, - stateSecondRound: map[string]interface{}(map[string]interface{}{ + stateSecondRound: map[string]any(map[string]any{ "FeedID": int64(1), "Time": decimal.NewFromInt(10), }), @@ -1967,7 +1968,7 @@ func TestAggregateShouldReport(t *testing.T) { require.NoError(t, err) state, err := vmap.Unwrap() require.NoError(t, err) - require.Equal(t, map[string]interface{}(tc.stateFirstRound), state) + require.Equal(t, map[string]any(tc.stateFirstRound), state) // 2nd round secondOutcome, err := agg.Aggregate(logger.Nop(), firstOutcome, map[commontypes.OracleID][]values.Value{1: {tc.mockValueSecondRound}, 2: {tc.mockValueSecondRound}, 3: {tc.mockValueSecondRound}}, 1) @@ -2008,9 +2009,7 @@ func getConfigReduceAggregator(t *testing.T, fields []aggregators.AggregationFie "outputFieldName": "Reports", "reportFormat": "array", } - for key, val := range override { - unwrappedConfig[key] = val - } + maps.Copy(unwrappedConfig, override) config, err := values.NewMap(unwrappedConfig) require.NoError(t, err) return config diff --git a/pkg/capabilities/consensus/ocr3/batching_test.go b/pkg/capabilities/consensus/ocr3/batching_test.go index eaab2922cf..a2d1282991 100644 --- a/pkg/capabilities/consensus/ocr3/batching_test.go +++ b/pkg/capabilities/consensus/ocr3/batching_test.go @@ -401,7 +401,7 @@ func TestQueryBatchHasCapacityCaching(t *testing.T) { func TestQueryBatchHasCapacityPerformance(t *testing.T) { // Performance test with many IDs ids := make([]*pbtypes.Id, 100) - for i := 0; i < 100; i++ { + for i := range 100 { ids[i] = &pbtypes.Id{ WorkflowExecutionId: "exec-" + string(rune('A'+i%26)), WorkflowId: "workflow-1", diff --git a/pkg/capabilities/consensus/ocr3/benchmark_test.go b/pkg/capabilities/consensus/ocr3/benchmark_test.go index 238c6980dd..be41436a87 100644 --- a/pkg/capabilities/consensus/ocr3/benchmark_test.go +++ b/pkg/capabilities/consensus/ocr3/benchmark_test.go @@ -118,7 +118,7 @@ func runObservationBenchmarkWithParams(b *testing.B, lggr logger.Logger, numWork } // Create LLO aggregators for each workflow and populate the store - for i := 0; i < numWorkflows; i++ { + for i := range numWorkflows { workflowID := fmt.Sprintf("workflow-%d", i) executionID := fmt.Sprintf("execution-%d", i) @@ -133,7 +133,7 @@ func runObservationBenchmarkWithParams(b *testing.B, lggr logger.Logger, numWork require.NoError(b, err) // Create list with the LLO event - listVal, err := values.NewList([]interface{}{wrappedEvent}) + listVal, err := values.NewList([]any{wrappedEvent}) require.NoError(b, err) // Create and add request to store @@ -179,7 +179,7 @@ func runObservationBenchmarkWithParams(b *testing.B, lggr logger.Logger, numWork } // Reset timer and enable memory allocation reporting - b.ResetTimer() + b.ReportAllocs() // Preallocate memory stats variables @@ -190,7 +190,7 @@ func runObservationBenchmarkWithParams(b *testing.B, lggr logger.Logger, numWork var totalObservationSize int // Run the benchmark - for i := 0; i < b.N; i++ { + for b.Loop() { runtime.GC() // Run garbage collection before measurement to reduce noise runtime.ReadMemStats(&memStatsBefore) @@ -241,7 +241,7 @@ func runBenchmarkWithParams(b *testing.B, lggr logger.Logger, numWorkflows, numS } // Create LLO aggregators for each workflow - for i := 0; i < numWorkflows; i++ { + for i := range numWorkflows { workflowID := fmt.Sprintf("workflow-%d", i) agg, err := createLLOAggregator(b, numStreamsPerWorkflow) require.NoError(b, err) @@ -282,11 +282,11 @@ func runBenchmarkWithParams(b *testing.B, lggr logger.Logger, numWorkflows, numS } // Reset timer and enable memory allocation reporting - b.ResetTimer() + b.ReportAllocs() // Run the benchmark - for i := 0; i < b.N; i++ { + for b.Loop() { var memStatsBefore, memStatsAfter runtime.MemStats runtime.ReadMemStats(&memStatsBefore) @@ -318,7 +318,7 @@ func runBenchmarkWithParams(b *testing.B, lggr logger.Logger, numWorkflows, numS // createTestQuery generates a query with the specified number of workflow IDs func createTestQuery(numWorkflows int) ([]byte, error) { ids := make([]*pbtypes.Id, numWorkflows) - for i := 0; i < numWorkflows; i++ { + for i := range numWorkflows { ids[i] = &pbtypes.Id{ WorkflowExecutionId: fmt.Sprintf("execution-%d", i), WorkflowId: fmt.Sprintf("workflow-%d", i), @@ -354,7 +354,7 @@ func createTestPreviousOutcome(numWorkflows, numStreamsPerWorkflow int) ([]byte, baseTime := time.Now().Add(-10 * time.Minute).UnixNano() zeroPrice, _ := decimal.Zero.MarshalBinary() - for i := 0; i < numStreamsPerWorkflow; i++ { + for i := range numStreamsPerWorkflow { streamID := uint32(i) baseMetadata.StreamInfo[streamID] = &datafeeds.LLOStreamInfo{ Timestamp: baseTime, @@ -369,7 +369,7 @@ func createTestPreviousOutcome(numWorkflows, numStreamsPerWorkflow int) ([]byte, } // Create outcome entries for each workflow, using the same metadata - for i := 0; i < numWorkflows; i++ { + for i := range numWorkflows { workflowID := fmt.Sprintf("workflow-%d", i) outcome.Outcomes[workflowID] = &pbtypes.AggregationOutcome{ Metadata: metadataBytes, @@ -387,7 +387,7 @@ func createTestPreviousOutcome(numWorkflows, numStreamsPerWorkflow int) ([]byte, func createTestAttributedObservations(b *testing.B, numOracles, numWorkflows, numStreamsPerWorkflow int) []types.AttributedObservation { aos := make([]types.AttributedObservation, numOracles) ts := timestamppb.Now() // Use a consistent timestamp for all observations to ensure consensus - for oracle := 0; oracle < numOracles; oracle++ { + for oracle := range numOracles { observationsProto := &pbtypes.Observations{ Observations: make([]*pbtypes.Observation, numWorkflows), RegisteredWorkflowIds: make([]string, numWorkflows), @@ -395,7 +395,7 @@ func createTestAttributedObservations(b *testing.B, numOracles, numWorkflows, nu } // Create an observation for each workflow - for i := 0; i < numWorkflows; i++ { + for i := range numWorkflows { workflowID := fmt.Sprintf("workflow-%d", i) executionID := fmt.Sprintf("execution-%d", i) observationsProto.RegisteredWorkflowIds[i] = workflowID @@ -406,7 +406,7 @@ func createTestAttributedObservations(b *testing.B, numOracles, numWorkflows, nu require.NoError(b, err) // Create list value with the LLO event - listVal, err := values.NewList([]interface{}{wrappedEvent}) + listVal, err := values.NewList([]any{wrappedEvent}) require.NoError(b, err) listProto := values.Proto(listVal).GetListValue() @@ -451,7 +451,7 @@ func createLLOEvent(b *testing.B, numStreams int, ts time.Time) *datastreams.LLO } // Create stream values with consistent prices - for i := 0; i < numStreams; i++ { + for i := range numStreams { price := decimal.NewFromInt(int64(100 + i%10)) // Use a few different price values binary, err := price.MarshalBinary() require.NoError(b, err) @@ -469,7 +469,7 @@ func createLLOEvent(b *testing.B, numStreams int, ts time.Time) *datastreams.LLO func createLLOAggregator(b *testing.B, numStreams int) (pbtypes.Aggregator, error) { // Create feed configs for all streams streamConfigs := make(map[string]datafeeds.FeedConfig, numStreams) - for i := 0; i < numStreams; i++ { + for i := range numStreams { streamConfigs[fmt.Sprintf("%d", i)] = datafeeds.FeedConfig{ // Deviation: decimal.NewFromFloat(0.01), // 1% deviation threshold Heartbeat: 3600, // 1 hour heartbeat diff --git a/pkg/capabilities/consensus/ocr3/datafeeds/example_llo_aggregator_test.go b/pkg/capabilities/consensus/ocr3/datafeeds/example_llo_aggregator_test.go index 5caada1f35..e21ca5d79f 100644 --- a/pkg/capabilities/consensus/ocr3/datafeeds/example_llo_aggregator_test.go +++ b/pkg/capabilities/consensus/ocr3/datafeeds/example_llo_aggregator_test.go @@ -24,14 +24,14 @@ func ExampleLLOAggregator_Aggregate() { panic(err) } // 1. Create aggregator with 2 stream configs - configMap, _ := values.NewMap(map[string]interface{}{ - "streams": map[string]interface{}{ - "1": map[string]interface{}{ + configMap, _ := values.NewMap(map[string]any{ + "streams": map[string]any{ + "1": map[string]any{ "deviation": "0.01", // 1% deviation threshold "heartbeat": 3600, // 1 hour heartbeat "remappedID": "0x680084f7347baFfb5C323c2982dfC90e04F9F918", }, - "2": map[string]interface{}{ + "2": map[string]any{ "deviation": "0.02", // 2% deviation threshold "heartbeat": 1800, // 30 min heartbeat "remappedID": "0x00001237347baFfb5C323c1112dfC90e0789FFFF", diff --git a/pkg/capabilities/consensus/ocr3/datafeeds/feeds_aggregator.go b/pkg/capabilities/consensus/ocr3/datafeeds/feeds_aggregator.go index e76adbb95e..56fe002e39 100644 --- a/pkg/capabilities/consensus/ocr3/datafeeds/feeds_aggregator.go +++ b/pkg/capabilities/consensus/ocr3/datafeeds/feeds_aggregator.go @@ -6,7 +6,7 @@ import ( "fmt" "math" "math/big" - "sort" + "slices" "strings" "time" @@ -132,7 +132,7 @@ func (a *dataFeedsAggregator) Aggregate(lggr logger.Logger, previousOutcome *typ lggr.Debugw("determined feeds to check", "nFeedIds", len(allIDs)) // ensure deterministic order of reportsNeedingUpdate - sort.Slice(allIDs, func(i, j int) bool { return allIDs[i] < allIDs[j] }) + slices.Sort(allIDs) candidateIDs := []string{} for _, feedIDStr := range allIDs { previousReportInfo := currentState.FeedInfo[feedIDStr] diff --git a/pkg/capabilities/consensus/ocr3/reporting_plugin_test.go b/pkg/capabilities/consensus/ocr3/reporting_plugin_test.go index 05826be0e1..e536c71031 100644 --- a/pkg/capabilities/consensus/ocr3/reporting_plugin_test.go +++ b/pkg/capabilities/consensus/ocr3/reporting_plugin_test.go @@ -3,7 +3,7 @@ package ocr3 import ( "context" "errors" - "sort" + "slices" "testing" "time" @@ -202,8 +202,8 @@ func TestReportingPlugin_Observation(t *testing.T) { assert.Equal(t, o, lvp) expected := []string{workflowTestID, workflowTestID2} actual := obspb.RegisteredWorkflowIds - sort.Slice(actual, func(i, j int) bool { return actual[i] < actual[j] }) - sort.Slice(expected, func(i, j int) bool { return expected[i] < expected[j] }) + slices.Sort(actual) + slices.Sort(expected) assert.Equal(t, expected, actual) } diff --git a/pkg/capabilities/consensus/ocr3/validation_service.go b/pkg/capabilities/consensus/ocr3/validation_service.go index ce9c5eb711..3a7a5806fe 100644 --- a/pkg/capabilities/consensus/ocr3/validation_service.go +++ b/pkg/capabilities/consensus/ocr3/validation_service.go @@ -15,7 +15,7 @@ type validationService struct { services.StateMachine } -func (v *validationService) ValidateConfig(ctx context.Context, config map[string]interface{}) error { +func (v *validationService) ValidateConfig(ctx context.Context, config map[string]any) error { return nil } diff --git a/pkg/capabilities/consensus/requests/store.go b/pkg/capabilities/consensus/requests/store.go index 887db7c95d..13acd7535b 100644 --- a/pkg/capabilities/consensus/requests/store.go +++ b/pkg/capabilities/consensus/requests/store.go @@ -107,10 +107,7 @@ func (s *Store[T]) RangeN(start, batchSize int) ([]T, error) { return nil, fmt.Errorf("start index out of bounds: start=%d, len=%d", start, len(s.requestIDs)) } - end := start + batchSize - if end > len(s.requestIDs) { - end = len(s.requestIDs) - } + end := min(start+batchSize, len(s.requestIDs)) got := make([]T, 0, end-start) for _, r := range s.requestIDs[start:end] { diff --git a/pkg/capabilities/consensus/requests/store_test.go b/pkg/capabilities/consensus/requests/store_test.go index 28ba237904..a00606c985 100644 --- a/pkg/capabilities/consensus/requests/store_test.go +++ b/pkg/capabilities/consensus/requests/store_test.go @@ -55,7 +55,7 @@ func TestOCR3Store(t *testing.T) { }) t.Run("firstN, batchSize larger than queue", func(t *testing.T) { - for i := 0; i < 10; i++ { + for range 10 { err := s.Add(&ocr3.ReportRequest{WorkflowExecutionID: uuid.New().String(), ExpiresAt: n.Add(1 * time.Hour)}) require.NoError(t, err) } @@ -77,7 +77,7 @@ func TestOCR3Store(t *testing.T) { }) t.Run("rangeN, batchSize larger than queue with start offset", func(t *testing.T) { - for i := 0; i < 10; i++ { + for range 10 { err := s.Add(&ocr3.ReportRequest{WorkflowExecutionID: uuid.New().String(), ExpiresAt: n.Add(1 * time.Hour)}) require.NoError(t, err) } diff --git a/pkg/capabilities/triggers/mercury_trigger.go b/pkg/capabilities/triggers/mercury_trigger.go index c95c7c8588..0853482bd8 100644 --- a/pkg/capabilities/triggers/mercury_trigger.go +++ b/pkg/capabilities/triggers/mercury_trigger.go @@ -174,10 +174,7 @@ func (o *MercuryTriggerService) loop() { func getNextWaitIntervalMs(lastTs, tickerResolutionMs, currentTs int64) int64 { desiredNext := lastTs + tickerResolutionMs - nextWait := desiredNext - currentTs - if nextWait <= 0 { - nextWait = 0 - } + nextWait := max(desiredNext-currentTs, 0) return nextWait } diff --git a/pkg/capabilities/triggers/mercury_trigger_test.go b/pkg/capabilities/triggers/mercury_trigger_test.go index 5e8e56b4a9..07442c016c 100644 --- a/pkg/capabilities/triggers/mercury_trigger_test.go +++ b/pkg/capabilities/triggers/mercury_trigger_test.go @@ -30,7 +30,7 @@ func registerTrigger( <-chan capabilities.TriggerResponse, capabilities.TriggerRegistrationRequest, ) { - config, err := values.NewMap(map[string]interface{}{ + config, err := values.NewMap(map[string]any{ "feedIds": feedIDs, "maxFrequencyMs": 100, }) @@ -221,7 +221,7 @@ func TestMercuryTrigger_RegisterTriggerErrors(t *testing.T) { ctx := t.Context() require.NoError(t, ts.Start(ctx)) - cm := map[string]interface{}{ + cm := map[string]any{ "feedIds": []string{feedOne}, "maxFrequencyMs": 90, } @@ -238,7 +238,7 @@ func TestMercuryTrigger_RegisterTriggerErrors(t *testing.T) { _, err = ts.RegisterTrigger(ctx, cr) require.Error(t, err) - cm = map[string]interface{}{ + cm = map[string]any{ "feedIds": []string{feedOne}, "maxFrequencyMs": 0, } @@ -248,7 +248,7 @@ func TestMercuryTrigger_RegisterTriggerErrors(t *testing.T) { _, err = ts.RegisterTrigger(ctx, cr) require.Error(t, err) - cm = map[string]interface{}{ + cm = map[string]any{ "feedIds": []string{}, "maxFrequencyMs": 1000, } @@ -282,7 +282,7 @@ func upwrapTriggerEvent(t *testing.T, req capabilities.TriggerResponse) (capabil func TestMercuryTrigger_ConfigValidation(t *testing.T) { var newConfig = func(t *testing.T, feedIDs []string, maxFrequencyMs int) *values.Map { - cm := map[string]interface{}{ + cm := map[string]any{ "feedIds": feedIDs, "maxFrequencyMs": maxFrequencyMs, } @@ -341,13 +341,13 @@ func TestMercuryTrigger_WrapReports(t *testing.T) { P := 50 // feeds B := 1000 // report size in bytes meta := datastreams.Metadata{} - for i := 0; i < S; i++ { + for range S { meta.Signers = append(meta.Signers, randomByteArray(t, 20)) } reportList := []datastreams.FeedReport{} - for i := 0; i < P; i++ { + for range P { signatures := [][]byte{} - for j := 0; j < S; j++ { + for range S { signatures = append(signatures, randomByteArray(t, 65)) } reportList = append(reportList, datastreams.FeedReport{ diff --git a/pkg/capabilities/v2/chain-capabilities/evm/proto_helpers_test.go b/pkg/capabilities/v2/chain-capabilities/evm/proto_helpers_test.go index 53aa4dcc29..b6f2911936 100644 --- a/pkg/capabilities/v2/chain-capabilities/evm/proto_helpers_test.go +++ b/pkg/capabilities/v2/chain-capabilities/evm/proto_helpers_test.go @@ -14,28 +14,28 @@ import ( func h32(b byte) evmtypes.Hash { var h [32]byte - for i := 0; i < 32; i++ { + for i := range 32 { h[i] = b + byte(i) } return h } func a20(b byte) evmtypes.Address { var a [20]byte - for i := 0; i < 20; i++ { + for i := range 20 { a[i] = b + byte(i) } return a } func b32(b byte) []byte { out := make([]byte, 32) - for i := 0; i < 32; i++ { + for i := range 32 { out[i] = b + byte(i) } return out } func b20(b byte) []byte { out := make([]byte, 20) - for i := 0; i < 20; i++ { + for i := range 20 { out[i] = b + byte(i) } return out diff --git a/pkg/capabilities/validate.go b/pkg/capabilities/validate.go index c0fb5dd79c..83d6ed1bb4 100644 --- a/pkg/capabilities/validate.go +++ b/pkg/capabilities/validate.go @@ -97,9 +97,9 @@ func (v *Validator[Config, Inputs, Outputs]) Schema() (string, error) { } ci := combinedWithInputs{} - var config interface{} = c.Config - var inputs interface{} = c.Inputs - var outputs interface{} = c.Outputs + var config any = c.Config + var inputs any = c.Inputs + var outputs any = c.Outputs if config == nil { return "", errors.New("config is nil, please provide a config type") } diff --git a/pkg/capabilities/validate_test.go b/pkg/capabilities/validate_test.go index 2a877b99e3..cbe99e960b 100644 --- a/pkg/capabilities/validate_test.go +++ b/pkg/capabilities/validate_test.go @@ -57,7 +57,7 @@ func TestValidator_Schema(t *testing.T) { func TestValidator_ValidateSchema(t *testing.T) { v, err := values.NewMap( - map[string]interface{}{ + map[string]any{ "feedIds": []string{"0x1111111111111111111100000000000000000000000000000000000000000000"}, }, ) @@ -91,7 +91,7 @@ func TestValidator_ValidateSchema(t *testing.T) { assert.NotNil(t, result) v, err = values.NewMap( - map[string]interface{}{ + map[string]any{ "feedIds": []string{"0x111111111111111111110F000000000000000000000000000000000000000000"}, }, ) @@ -103,17 +103,17 @@ func TestValidator_ValidateSchema(t *testing.T) { } func TestValidator_ValidateConfig(t *testing.T) { - m, err := values.NewMap(map[string]interface{}{ + m, err := values.NewMap(map[string]any{ "baz": "world", }) assert.NoError(t, err) - l, err := values.NewList([]interface{}{"hello", "world"}) + l, err := values.NewList([]any{"hello", "world"}) assert.NoError(t, err) v := NewValidator[TestConfig, TestInputs, TestOutputs](ValidatorArgs{}) config, err := values.NewMap( - map[string]interface{}{ + map[string]any{ "foo": l, "bar": 123, "bonk": m, @@ -139,7 +139,7 @@ func TestValidator_ValidateConfig(t *testing.T) { func TestValidator_ValidateInputs(t *testing.T) { v := NewValidator[TestConfig, TestInputs, TestOutputs](ValidatorArgs{}) inputs, err := values.NewMap( - map[string]interface{}{ + map[string]any{ "baz": "world", "qux": 456, }, @@ -150,7 +150,7 @@ func TestValidator_ValidateInputs(t *testing.T) { assert.NotNil(t, result) inputs, err = values.NewMap( - map[string]interface{}{ + map[string]any{ "baz": "world", "qux": -1, }, @@ -161,7 +161,7 @@ func TestValidator_ValidateInputs(t *testing.T) { assert.NotNil(t, result) inputs, err = values.NewMap( - map[string]interface{}{ + map[string]any{ "baz": "worl", "qux": -1, }, @@ -176,7 +176,7 @@ func TestValidator_ValidateOutputs(t *testing.T) { v := NewValidator[TestConfig, TestInputs, TestOutputs](ValidatorArgs{}) outputs, err := values.NewMap( - map[string]interface{}{ + map[string]any{ "quux": "world", "corge": 456, }, @@ -187,7 +187,7 @@ func TestValidator_ValidateOutputs(t *testing.T) { assert.NotNil(t, result) outputs, err = values.NewMap( - map[string]interface{}{ + map[string]any{ "quux": "world", "corge": 0, }, @@ -256,7 +256,7 @@ func TestValidator_GenerateSchema(t *testing.T) { var transformJSON = cmp.FilterValues(func(x, y []byte) bool { return json.Valid(x) && json.Valid(y) -}, cmp.Transformer("ParseJSON", func(in []byte) (out interface{}) { +}, cmp.Transformer("ParseJSON", func(in []byte) (out any) { if err := json.Unmarshal(in, &out); err != nil { panic(err) // should never occur given previous filter to ensure valid JSON } diff --git a/pkg/codec/config.go b/pkg/codec/config.go index f052e4c58f..59a0138bce 100644 --- a/pkg/codec/config.go +++ b/pkg/codec/config.go @@ -501,7 +501,7 @@ func (h *modifierMarshaller[T]) MarshalJSON() ([]byte, error) { v := reflect.Indirect(reflect.ValueOf(h.T)) t := v.Type() - m := map[string]interface{}{ + m := map[string]any{ "Type": h.Type, } diff --git a/pkg/codec/encodings/binary/gen/main.go b/pkg/codec/encodings/binary/gen/main.go index 8e47fcc00b..159b011aad 100644 --- a/pkg/codec/encodings/binary/gen/main.go +++ b/pkg/codec/encodings/binary/gen/main.go @@ -39,13 +39,13 @@ func main() { panic(err) } - res = []byte( - fmt.Sprintf( + res = + fmt.Appendf(nil, "// DO NOT MODIFY: automatically generated from %s/main.go using the template %s\n\n%s", location, gen.fileName, string(res), - )) + ) if err = os.WriteFile(gen.fileName, res, 0600); err != nil { panic(err) diff --git a/pkg/codec/encodings/utils.go b/pkg/codec/encodings/utils.go index 3d9b2540b8..f9095a0585 100644 --- a/pkg/codec/encodings/utils.go +++ b/pkg/codec/encodings/utils.go @@ -7,7 +7,7 @@ import ( "github.com/smartcontractkit/chainlink-common/pkg/types" ) -func SafeDecode[T interface{}](raw []byte, size int, call func([]byte) T) (T, []byte, error) { +func SafeDecode[T any](raw []byte, size int, call func([]byte) T) (T, []byte, error) { if len(raw) < size { var t T return t, nil, fmt.Errorf("%w: not enough bytes to decode type", types.ErrInvalidEncoding) @@ -23,7 +23,7 @@ func EncodeEach(value reflect.Value, into []byte, tc TypeCodec) ([]byte, error) } numElements := value.Len() - for i := 0; i < numElements; i++ { + for i := range numElements { var err error into, err = tc.Encode(value.Index(i).Interface(), into) if err != nil { @@ -45,7 +45,7 @@ func DecodeEach(encoded []byte, into reflect.Value, numElements int, tc TypeCode } remaining := encoded - for i := 0; i < numElements; i++ { + for i := range numElements { element, bytes, err := tc.Decode(remaining) if err != nil { return nil, nil, err diff --git a/pkg/codec/field_and_indices.go b/pkg/codec/field_and_indices.go index fcb43356ef..d7bdc60d8d 100644 --- a/pkg/codec/field_and_indices.go +++ b/pkg/codec/field_and_indices.go @@ -34,7 +34,7 @@ func getFieldIndices(inputType reflect.Type) (*fieldsAndIndices, error) { fields := make([]reflect.StructField, length) Indices := map[string]int{} - for i := 0; i < length; i++ { + for i := range length { field := inputType.Field(i) Indices[field.Name] = i fields[i] = field diff --git a/pkg/codec/hard_coder.go b/pkg/codec/hard_coder.go index 12463afbf8..44e6725227 100644 --- a/pkg/codec/hard_coder.go +++ b/pkg/codec/hard_coder.go @@ -189,7 +189,7 @@ func hardCodeManyHook(from reflect.Value, to reflect.Value) (any, error) { length := to.Len() array := reflect.MakeSlice(reflect.SliceOf(from.Type()), length, length) - for i := 0; i < length; i++ { + for i := range length { array.Index(i).Set(from) } return array.Interface(), nil diff --git a/pkg/codec/hard_coder_test.go b/pkg/codec/hard_coder_test.go index 526f2b10cd..748700a576 100644 --- a/pkg/codec/hard_coder_test.go +++ b/pkg/codec/hard_coder_test.go @@ -432,7 +432,7 @@ func TestHardCoder(t *testing.T) { }) t.Run("TransformToOnChain respect hooks", func(t *testing.T) { - var hook mapstructure.DecodeHookFunc = func(from, to reflect.Kind, val interface{}) (any, error) { + var hook mapstructure.DecodeHookFunc = func(from, to reflect.Kind, val any) (any, error) { if to == reflect.Int32 { return int32(123), nil } @@ -452,7 +452,7 @@ func TestHardCoder(t *testing.T) { }) t.Run("TransformToOffChain respect hooks", func(t *testing.T) { - var hook mapstructure.DecodeHookFunc = func(from, to reflect.Kind, val interface{}) (any, error) { + var hook mapstructure.DecodeHookFunc = func(from, to reflect.Kind, val any) (any, error) { if to == reflect.Int32 { return int32(123), nil } diff --git a/pkg/codec/modifier_base.go b/pkg/codec/modifier_base.go index f732e120a9..04049b2bc2 100644 --- a/pkg/codec/modifier_base.go +++ b/pkg/codec/modifier_base.go @@ -301,7 +301,7 @@ func transformWithMapsHelper[T any]( func doMany[T any](rInput, rOutput reflect.Value, fields map[string]T, fn mapAction[T], hooks []mapstructure.DecodeHookFunc) error { length := rInput.Len() - for i := 0; i < length; i++ { + for i := range length { // Make sure the items are addressable inTmp := rInput.Index(i) outTmp := rOutput.Index(i) diff --git a/pkg/codec/modifier_codec_test.go b/pkg/codec/modifier_codec_test.go index daff24704e..e878a41fba 100644 --- a/pkg/codec/modifier_codec_test.go +++ b/pkg/codec/modifier_codec_test.go @@ -255,7 +255,7 @@ func (t *testCodec) Decode(_ context.Context, raw []byte, into any, itemType str case anySliceItemType: items := make([]modifierCodecChainType, anyValue) reflect.Indirect(reflect.ValueOf(into)).Set(reflect.ValueOf(items)) - for i := 0; i < anyValue; i++ { + for i := range anyValue { items[i].A = anyValue + i } default: diff --git a/pkg/codec/property_extractor.go b/pkg/codec/property_extractor.go index 8469b16c29..7a1c12e4a2 100644 --- a/pkg/codec/property_extractor.go +++ b/pkg/codec/property_extractor.go @@ -349,7 +349,7 @@ type extractOrExpandHelperFunc func(reflect.Value, reflect.Type, string) (reflec func extractOrExpandMany(rInput, rOutput reflect.Value, field string, fn extractOrExpandHelperFunc) error { length := rInput.Len() - for i := 0; i < length; i++ { + for i := range length { inTmp := rInput.Index(i) outTmp := rOutput.Index(i) diff --git a/pkg/codec/utils.go b/pkg/codec/utils.go index f18fc2a124..0446bd6d11 100644 --- a/pkg/codec/utils.go +++ b/pkg/codec/utils.go @@ -205,7 +205,7 @@ var ( timeType = reflect.TypeOf(time.Time{}) timePtrType = reflect.PointerTo(timeType) biType = reflect.TypeOf(&big.Int{}) - mapType = reflect.TypeOf(map[string]interface{}{}) + mapType = reflect.TypeOf(map[string]any{}) ptrMapType = reflect.PointerTo(mapType) interMapKey = "IntermediateEpochMapKey" ) @@ -224,7 +224,7 @@ func EpochToTimeHook(from reflect.Type, to reflect.Type, data any) (any, error) return data, nil case mapType, ptrMapType: // map to int64 - timeMap, ok := reflect.Indirect(reflect.ValueOf(data)).Interface().(map[string]interface{}) + timeMap, ok := reflect.Indirect(reflect.ValueOf(data)).Interface().(map[string]any) if !ok { return data, nil } @@ -329,7 +329,7 @@ func getMapsFromPath(valueMap map[string]any, path []string) ([]map[string]any, case reflect.Array, reflect.Slice: length := iItem.Len() maps := make([]map[string]any, length) - for i := 0; i < length; i++ { + for i := range length { if err := mapstructure.Decode(iItem.Index(i).Interface(), &maps[i]); err != nil { return nil, fmt.Errorf("%w: %w", types.ErrInvalidType, err) } diff --git a/pkg/codec/utils_test.go b/pkg/codec/utils_test.go index 382c1f7b83..c43e32b5ea 100644 --- a/pkg/codec/utils_test.go +++ b/pkg/codec/utils_test.go @@ -45,14 +45,14 @@ func TestGetMapsFromPath(t *testing.T) { actual, err = getMapsFromPath(testMap, []string{"A", "B"}) require.NoError(t, err) - assert.Equal(t, []map[string]interface{}{ + assert.Equal(t, []map[string]any{ { - "A": map[string]interface{}{"IntSlice": []int(nil)}, - "B": map[string]interface{}{"TestASlice": []testA{{IntSlice: []int{3, 2, 0}}, {IntSlice: []int{0, 1, 2}}}}, - "C": map[string]interface{}{"TestAPtrSlice": ptrSlice}, "D": 10, "F": 100}, + "A": map[string]any{"IntSlice": []int(nil)}, + "B": map[string]any{"TestASlice": []testA{{IntSlice: []int{3, 2, 0}}, {IntSlice: []int{0, 1, 2}}}}, + "C": map[string]any{"TestAPtrSlice": ptrSlice}, "D": 10, "F": 100}, { - "A": map[string]interface{}{"IntSlice": []int(nil)}, - "B": map[string]interface{}{"TestASlice": []testA(nil)}, "C": map[string]interface{}{"TestAPtrSlice": (*[]testA)(nil)}, "D": 20, "F": 200, + "A": map[string]any{"IntSlice": []int(nil)}, + "B": map[string]any{"TestASlice": []testA(nil)}, "C": map[string]any{"TestAPtrSlice": (*[]testA)(nil)}, "D": 20, "F": 200, }, }, actual) diff --git a/pkg/config/bytes.go b/pkg/config/bytes.go index d1df2fd3eb..5725367992 100644 --- a/pkg/config/bytes.go +++ b/pkg/config/bytes.go @@ -43,18 +43,18 @@ func SizeOf[B ~[]byte](bs ...B) (s Size) { func (b Size) MarshalText() ([]byte, error) { if b >= TByte { d := decimal.NewFromInt(int64(b)).Div(decimal.NewFromInt(int64(TByte))) - return []byte(fmt.Sprintf("%stb", d)), nil + return fmt.Appendf(nil, "%stb", d), nil } else if b >= GByte { d := decimal.NewFromInt(int64(b)).Div(decimal.NewFromInt(int64(GByte))) - return []byte(fmt.Sprintf("%sgb", d)), nil + return fmt.Appendf(nil, "%sgb", d), nil } else if b >= MByte { d := decimal.NewFromInt(int64(b)).Div(decimal.NewFromInt(int64(MByte))) - return []byte(fmt.Sprintf("%smb", d)), nil + return fmt.Appendf(nil, "%smb", d), nil } else if b >= KByte { d := decimal.NewFromInt(int64(b)).Div(decimal.NewFromInt(int64(KByte))) - return []byte(fmt.Sprintf("%skb", d)), nil + return fmt.Appendf(nil, "%skb", d), nil } - return []byte(fmt.Sprintf("%db", b)), nil + return fmt.Appendf(nil, "%db", b), nil } func ParseByte(s string) (b Size, err error) { diff --git a/pkg/config/bytes_test.go b/pkg/config/bytes_test.go index 51e4b8f8e4..89e945918a 100644 --- a/pkg/config/bytes_test.go +++ b/pkg/config/bytes_test.go @@ -29,7 +29,6 @@ func TestBytes_MarshalText_String(t *testing.T) { } for _, test := range tests { - test := test t.Run(test.expected, func(t *testing.T) { t.Parallel() @@ -78,7 +77,6 @@ func TestBytes_UnmarshalText(t *testing.T) { } for _, test := range tests { - test := test t.Run(test.input, func(t *testing.T) { t.Parallel() diff --git a/pkg/config/configdoc/configdoc.go b/pkg/config/configdoc/configdoc.go index 95714193bb..c4e6ab6b49 100644 --- a/pkg/config/configdoc/configdoc.go +++ b/pkg/config/configdoc/configdoc.go @@ -167,7 +167,7 @@ func parseTOMLDocs(s string, extendedDescriptions map[string]string) (items []fm currentTable := &globalTable items = append(items, currentTable) var desc lines - for _, line := range strings.Split(s, "\n") { + for line := range strings.SplitSeq(s, "\n") { if strings.HasPrefix(line, "#") { // comment desc = append(desc, strings.TrimSpace(line[1:])) diff --git a/pkg/config/configtest/configtest.go b/pkg/config/configtest/configtest.go index 95ae52af57..d8c35e08a2 100644 --- a/pkg/config/configtest/configtest.go +++ b/pkg/config/configtest/configtest.go @@ -17,14 +17,14 @@ import ( ) // AssertFieldsNotNil recursively checks s for nil fields. s must be a struct. -func AssertFieldsNotNil(t *testing.T, s interface{}) { +func AssertFieldsNotNil(t *testing.T, s any) { _, err := CheckFieldsNotNil(t, s) assert.NoError(t, err) } // CheckFieldsNotNil recursively checks s for nil fields. s must be a struct. // Returns the number of nil fields found and an error describing them. -func CheckFieldsNotNil(t *testing.T, s interface{}) (int, error) { +func CheckFieldsNotNil(t *testing.T, s any) (int, error) { t.Helper() err := assertValNotNil(t, "", reflect.ValueOf(s)) return config.MultiErrorList(err) diff --git a/pkg/config/duration.go b/pkg/config/duration.go index ed6ebf3f4f..e45f9dcc45 100644 --- a/pkg/config/duration.go +++ b/pkg/config/duration.go @@ -80,7 +80,7 @@ func (d *Duration) UnmarshalJSON(input []byte) error { return nil } -func (d *Duration) Scan(v interface{}) (err error) { +func (d *Duration) Scan(v any) (err error) { switch tv := v.(type) { case int64: *d, err = NewDuration(time.Duration(tv)) diff --git a/pkg/config/rate.go b/pkg/config/rate.go index 9f7a655c68..382ecf017f 100644 --- a/pkg/config/rate.go +++ b/pkg/config/rate.go @@ -25,8 +25,8 @@ func ParseRate(s string) (Rate, error) { return Rate{}, fmt.Errorf("invalid rate limit: %s: must contain two parts", s) } var rateLimit Rate - if strings.HasPrefix(parts[0], "every") { // optional format every - limit := strings.TrimPrefix(parts[0], "every") + if after, ok := strings.CutPrefix(parts[0], "every"); ok { // optional format every + limit := after d, err := time.ParseDuration(limit) if err != nil { return Rate{}, err diff --git a/pkg/config/validate.go b/pkg/config/validate.go index 6fd9b09f9c..8e3c083a40 100644 --- a/pkg/config/validate.go +++ b/pkg/config/validate.go @@ -18,7 +18,7 @@ type Validated interface { } // Validate returns any errors from calling Validated.ValidateConfig on cfg and any nested types that implement Validated. -func Validate(cfg interface{}) (err error) { +func Validate(cfg any) (err error) { _, err = MultiErrorList(validate(reflect.ValueOf(cfg), true)) return } diff --git a/pkg/hashutil/keccak.go b/pkg/hashutil/keccak.go index 4b17feee65..0cdcfefee9 100644 --- a/pkg/hashutil/keccak.go +++ b/pkg/hashutil/keccak.go @@ -47,7 +47,7 @@ func (k keccak) HashInternal(a, b [32]byte) [32]byte { // This value is chosen since it is unlikely to be the result of a hash, and cannot match any internal node preimage. func (k keccak) ZeroHash() [32]byte { var zeroes [32]byte - for i := 0; i < 32; i++ { + for i := range 32 { zeroes[i] = 0xFF } return zeroes diff --git a/pkg/logger/logger_test.go b/pkg/logger/logger_test.go index 0950edb7f1..02797637eb 100644 --- a/pkg/logger/logger_test.go +++ b/pkg/logger/logger_test.go @@ -231,7 +231,7 @@ type other struct { *zap.SugaredLogger } -func (o *other) With(args ...interface{}) Logger { +func (o *other) With(args ...any) Logger { return &other{o.SugaredLogger.With(args...)} } @@ -249,13 +249,13 @@ func (o *other) Named(name string) Logger { return &newLogger } -func (o *other) Critical(args ...interface{}) { +func (o *other) Critical(args ...any) { o.WithOptions(zap.AddCallerSkip(1)).DPanic(args...) } -func (o *other) Criticalf(format string, values ...interface{}) { +func (o *other) Criticalf(format string, values ...any) { o.WithOptions(zap.AddCallerSkip(1)).DPanicf(format, values...) } -func (o *other) Criticalw(msg string, keysAndValues ...interface{}) { +func (o *other) Criticalw(msg string, keysAndValues ...any) { o.WithOptions(zap.AddCallerSkip(1)).DPanicw(msg, keysAndValues...) } @@ -263,7 +263,7 @@ type different struct { *zap.SugaredLogger } -func (d *different) With(args ...interface{}) differentLogger { +func (d *different) With(args ...any) differentLogger { return &different{d.SugaredLogger.With(args...)} } @@ -285,11 +285,11 @@ type mismatch struct { *zap.SugaredLogger } -func (m *mismatch) With(args ...interface{}) interface{} { +func (m *mismatch) With(args ...any) any { return &mismatch{m.SugaredLogger.With(args...)} } -func (m *mismatch) Helper(skip int) interface{} { +func (m *mismatch) Helper(skip int) any { return &mismatch{m.SugaredLogger.WithOptions(zap.AddCallerSkip(skip))} } @@ -301,26 +301,26 @@ type differentLogger interface { Name() string Named(string) Logger - Debug(args ...interface{}) - Info(args ...interface{}) - Warn(args ...interface{}) - Error(args ...interface{}) - Panic(args ...interface{}) - Fatal(args ...interface{}) - - Debugf(format string, values ...interface{}) - Infof(format string, values ...interface{}) - Warnf(format string, values ...interface{}) - Errorf(format string, values ...interface{}) - Panicf(format string, values ...interface{}) - Fatalf(format string, values ...interface{}) - - Debugw(msg string, keysAndValues ...interface{}) - Infow(msg string, keysAndValues ...interface{}) - Warnw(msg string, keysAndValues ...interface{}) - Errorw(msg string, keysAndValues ...interface{}) - Panicw(msg string, keysAndValues ...interface{}) - Fatalw(msg string, keysAndValues ...interface{}) + Debug(args ...any) + Info(args ...any) + Warn(args ...any) + Error(args ...any) + Panic(args ...any) + Fatal(args ...any) + + Debugf(format string, values ...any) + Infof(format string, values ...any) + Warnf(format string, values ...any) + Errorf(format string, values ...any) + Panicf(format string, values ...any) + Fatalf(format string, values ...any) + + Debugw(msg string, keysAndValues ...any) + Infow(msg string, keysAndValues ...any) + Warnw(msg string, keysAndValues ...any) + Errorw(msg string, keysAndValues ...any) + Panicw(msg string, keysAndValues ...any) + Fatalw(msg string, keysAndValues ...any) Sync() error } diff --git a/pkg/logger/ocr.go b/pkg/logger/ocr.go index 3343f184f6..cde2891ff7 100644 --- a/pkg/logger/ocr.go +++ b/pkg/logger/ocr.go @@ -52,8 +52,8 @@ func (o *ocrWrapper) Critical(msg string, fields ocrtypes.LogFields) { Criticalw(o.l, msg, toKeysAndValues(fields)...) } -func toKeysAndValues(fields ocrtypes.LogFields) []interface{} { - out := []interface{}{} +func toKeysAndValues(fields ocrtypes.LogFields) []any { + out := []any{} for key, val := range fields { out = append(out, key, val) } diff --git a/pkg/logger/sugared.go b/pkg/logger/sugared.go index d599220e6f..19ef137416 100644 --- a/pkg/logger/sugared.go +++ b/pkg/logger/sugared.go @@ -7,9 +7,9 @@ type SugaredLogger interface { Logger // AssumptionViolation variants log at error level with the message prefix "AssumptionViolation: ". - AssumptionViolation(args ...interface{}) - AssumptionViolationf(format string, vals ...interface{}) - AssumptionViolationw(msg string, keysAndVals ...interface{}) + AssumptionViolation(args ...any) + AssumptionViolationf(format string, vals ...any) + AssumptionViolationw(msg string, keysAndVals ...any) // ErrorIf logs the error if present. ErrorIf(err error, msg string) @@ -20,16 +20,16 @@ type SugaredLogger interface { ErrorIfFn(fn func() error, msg string) // Critical emits critical level logs (a remapping of [zap.DPanicLevel]) or falls back to error level with a '[crit]' prefix. - Critical(args ...interface{}) - Criticalf(format string, vals ...interface{}) - Criticalw(msg string, keysAndVals ...interface{}) + Critical(args ...any) + Criticalf(format string, vals ...any) + Criticalw(msg string, keysAndVals ...any) // Trace emits logs only when built with the 'trace' tag. // // go test -tags trace ./foo -run TestBar - Trace(args ...interface{}) - Tracef(format string, vals ...interface{}) - Tracew(msg string, keysAndVals ...interface{}) + Trace(args ...any) + Tracef(format string, vals ...any) + Tracew(msg string, keysAndVals ...any) // Named creates a new Logger sub-scoped with name. // Names are inherited and dot-separated. @@ -75,28 +75,28 @@ func (s *sugared) ErrorIfFn(fn func() error, msg string) { const assumptionViolationPrefix = "AssumptionViolation: " -func (s *sugared) AssumptionViolation(args ...interface{}) { - s.h.Error(append([]interface{}{assumptionViolationPrefix}, args...)) +func (s *sugared) AssumptionViolation(args ...any) { + s.h.Error(append([]any{assumptionViolationPrefix}, args...)) } -func (s *sugared) AssumptionViolationf(format string, vals ...interface{}) { +func (s *sugared) AssumptionViolationf(format string, vals ...any) { s.h.Errorf(assumptionViolationPrefix+format, vals...) } -func (s *sugared) AssumptionViolationw(msg string, keyvals ...interface{}) { +func (s *sugared) AssumptionViolationw(msg string, keyvals ...any) { s.h.Errorw(assumptionViolationPrefix+msg, keyvals...) } const critPrefix = "[crit] " -func (s *sugared) Critical(args ...interface{}) { +func (s *sugared) Critical(args ...any) { switch t := s.h.(type) { case *logger: t.DPanic(args...) return } c, ok := s.h.(interface { - Critical(args ...interface{}) + Critical(args ...any) }) if ok { c.Critical(args...) @@ -105,14 +105,14 @@ func (s *sugared) Critical(args ...interface{}) { s.h.Error(append([]any{critPrefix}, args...)...) } -func (s *sugared) Criticalf(format string, values ...interface{}) { +func (s *sugared) Criticalf(format string, values ...any) { switch t := s.h.(type) { case *logger: t.DPanicf(format, values...) return } c, ok := s.h.(interface { - Criticalf(format string, values ...interface{}) + Criticalf(format string, values ...any) }) if ok { c.Criticalf(format, values...) @@ -121,14 +121,14 @@ func (s *sugared) Criticalf(format string, values ...interface{}) { s.h.Errorf(critPrefix+format, values...) } -func (s *sugared) Criticalw(msg string, keysAndValues ...interface{}) { +func (s *sugared) Criticalw(msg string, keysAndValues ...any) { switch t := s.h.(type) { case *logger: t.DPanicw(msg, keysAndValues...) return } c, ok := s.h.(interface { - Criticalw(msg string, keysAndValues ...interface{}) + Criticalw(msg string, keysAndValues ...any) }) if ok { c.Criticalw(msg, keysAndValues...) @@ -141,7 +141,7 @@ func (s *sugared) Named(n string) SugaredLogger { return Sugared(Named(s.Logger, n)) } -func (s *sugared) With(keyvals ...interface{}) SugaredLogger { +func (s *sugared) With(keyvals ...any) SugaredLogger { return Sugared(With(s.Logger, keyvals...)) } diff --git a/pkg/logger/trace_noop.go b/pkg/logger/trace_noop.go index 63a967a4a4..e90d089639 100644 --- a/pkg/logger/trace_noop.go +++ b/pkg/logger/trace_noop.go @@ -2,23 +2,23 @@ package logger -func (s *sugared) Trace(args ...interface{}) {} +func (s *sugared) Trace(args ...any) {} -func (s *sugared) Tracef(format string, vals ...interface{}) {} +func (s *sugared) Tracef(format string, vals ...any) {} -func (s *sugared) Tracew(msg string, keysAndValues ...interface{}) {} +func (s *sugared) Tracew(msg string, keysAndValues ...any) {} // Deprecated: instead use [SugaredLogger.Trace]: // // Sugared(l).Trace(args...) -func Trace(l Logger, args ...interface{}) {} +func Trace(l Logger, args ...any) {} // Deprecated: instead use [SugaredLogger.Tracef]: // // Sugared(l).Tracef(args...) -func Tracef(l Logger, format string, values ...interface{}) {} +func Tracef(l Logger, format string, values ...any) {} // Deprecated: instead use [SugaredLogger.Tracew]: // // Sugared(l).Tracew(args...) -func Tracew(l Logger, msg string, keysAndValues ...interface{}) {} +func Tracew(l Logger, msg string, keysAndValues ...any) {} diff --git a/pkg/loop/ccip_commit.go b/pkg/loop/ccip_commit.go index 061a2a81b5..a467015c97 100644 --- a/pkg/loop/ccip_commit.go +++ b/pkg/loop/ccip_commit.go @@ -42,7 +42,7 @@ func (p *CommitLoop) GRPCServer(broker *plugin.GRPCBroker, server *grpc.Server) } // GRPCClient implements [plugin.GRPCPlugin] and returns the pluginClient [types.CCIPCommitFactoryGenerator], updated with the new broker and conn. -func (p *CommitLoop) GRPCClient(_ context.Context, broker *plugin.GRPCBroker, conn *grpc.ClientConn) (interface{}, error) { +func (p *CommitLoop) GRPCClient(_ context.Context, broker *plugin.GRPCBroker, conn *grpc.ClientConn) (any, error) { if p.pluginClient == nil { p.pluginClient = ccip.NewCommitLOOPClient(p.BrokerConfig) } diff --git a/pkg/loop/ccip_execution.go b/pkg/loop/ccip_execution.go index 5149b9d79e..5184522179 100644 --- a/pkg/loop/ccip_execution.go +++ b/pkg/loop/ccip_execution.go @@ -42,7 +42,7 @@ func (p *ExecutionLoop) GRPCServer(broker *plugin.GRPCBroker, server *grpc.Serve } // GRPCClient implements [plugin.GRPCPlugin] and returns the pluginClient [types.CCIPExecutionFactoryGenerator], updated with the new broker and conn. -func (p *ExecutionLoop) GRPCClient(_ context.Context, broker *plugin.GRPCBroker, conn *grpc.ClientConn) (interface{}, error) { +func (p *ExecutionLoop) GRPCClient(_ context.Context, broker *plugin.GRPCBroker, conn *grpc.ClientConn) (any, error) { if p.pluginClient == nil { p.pluginClient = ccip.NewExecutionLOOPClient(p.BrokerConfig) } diff --git a/pkg/loop/cmd/loopinstall/install.go b/pkg/loop/cmd/loopinstall/install.go index 740a281707..fe643c65ff 100644 --- a/pkg/loop/cmd/loopinstall/install.go +++ b/pkg/loop/cmd/loopinstall/install.go @@ -134,10 +134,10 @@ func downloadAndInstallPlugin(pluginType string, pluginIdx int, plugin PluginDef if installPath == moduleURI { // Case 1: installPath is the moduleURI itself. Install the module root. installArg = "." - } else if strings.HasPrefix(installPath, moduleURI+"/") { + } else if after, ok := strings.CutPrefix(installPath, moduleURI+"/"); ok { // Case 2: installPath is a sub-package of moduleURI (e.g., "moduleURI/cmd/plugin"). // Extract the relative path and prefix with "./". - relativePath := strings.TrimPrefix(installPath, moduleURI+"/") + relativePath := after cleanedRelativePath := strings.TrimLeft(relativePath, "/") // Handles "moduleURI///subpath" if cleanedRelativePath == "" || cleanedRelativePath == "." { // Handles "moduleURI/" or "moduleURI/." installArg = "." @@ -278,7 +278,7 @@ func installPlugins(tasks []PluginInstallTask, concurrency int, verbose bool, ou resultCh := make(chan PluginInstallResult, len(tasks)) var wg sync.WaitGroup - for i := 0; i < concurrency; i++ { + for i := range concurrency { wg.Add(1) go func(workerID int) { defer wg.Done() diff --git a/pkg/loop/internal/core/services/capability/capabilities_registry.go b/pkg/loop/internal/core/services/capability/capabilities_registry.go index e9448b988f..7070e687a9 100644 --- a/pkg/loop/internal/core/services/capability/capabilities_registry.go +++ b/pkg/loop/internal/core/services/capability/capabilities_registry.go @@ -45,7 +45,6 @@ func toDON(don *pb.DON) capabilities.DON { func toPbDON(don capabilities.DON) *pb.DON { membersBytes := make([][]byte, len(don.Members)) for j, m := range don.Members { - m := m membersBytes[j] = m[:] } diff --git a/pkg/loop/internal/core/services/pipeline/pipeline_runner_test.go b/pkg/loop/internal/core/services/pipeline/pipeline_runner_test.go index e30df4923b..6df63a86e9 100644 --- a/pkg/loop/internal/core/services/pipeline/pipeline_runner_test.go +++ b/pkg/loop/internal/core/services/pipeline/pipeline_runner_test.go @@ -67,7 +67,7 @@ func TestPipelineRunnerService(t *testing.T) { trs, err := client.ExecuteRun( ctx, "my-spec", - core.Vars{Vars: map[string]interface{}{"my-vars": true}}, + core.Vars{Vars: map[string]any{"my-vars": true}}, core.Options{MaxTaskDuration: 10 * time.Second}, ) require.NoError(t, err) @@ -82,7 +82,7 @@ func TestPipelineRunnerService_CallArgs(t *testing.T) { spec := "my-spec" vars := core.Vars{ - Vars: map[string]interface{}{"my-vars": true}, + Vars: map[string]any{"my-vars": true}, } options := core.Options{ MaxTaskDuration: 10 * time.Second, diff --git a/pkg/loop/internal/core/services/pipeline/test/pipeline_runner.go b/pkg/loop/internal/core/services/pipeline/test/pipeline_runner.go index b2685369b1..8ae1150fef 100644 --- a/pkg/loop/internal/core/services/pipeline/test/pipeline_runner.go +++ b/pkg/loop/internal/core/services/pipeline/test/pipeline_runner.go @@ -20,7 +20,7 @@ var PipelineRunner = staticPipelineRunnerService{ staticPipelineRunnerConfig: staticPipelineRunnerConfig{ spec: pipleineSpec, vars: core.Vars{ - Vars: map[string]interface{}{"foo": "baz"}, + Vars: map[string]any{"foo": "baz"}, }, options: core.Options{ MaxTaskDuration: 10 * time.Second, diff --git a/pkg/loop/internal/core/services/validation/test/validation.go b/pkg/loop/internal/core/services/validation/test/validation.go index 776d21c8a5..5b4cd8df06 100644 --- a/pkg/loop/internal/core/services/validation/test/validation.go +++ b/pkg/loop/internal/core/services/validation/test/validation.go @@ -11,7 +11,7 @@ import ( var ValidationService = staticValidationService{} -var GoodPluginConfig = map[string]interface{}{ +var GoodPluginConfig = map[string]any{ "isGoodConfig": true, "someFieldName": "someFieldValue", } @@ -26,7 +26,7 @@ func (t staticValidationService) Evaluate(ctx context.Context, other core.Valida return other.ValidateConfig(ctx, GoodPluginConfig) } -func (t staticValidationService) ValidateConfig(ctx context.Context, config map[string]interface{}) error { +func (t staticValidationService) ValidateConfig(ctx context.Context, config map[string]any) error { if !reflect.DeepEqual(GoodPluginConfig, config) { return fmt.Errorf("expected %+v but got %+v", GoodPluginConfig, config) } diff --git a/pkg/loop/internal/core/services/validation/validation.go b/pkg/loop/internal/core/services/validation/validation.go index 5112f25b2d..e06ad7f7ca 100644 --- a/pkg/loop/internal/core/services/validation/validation.go +++ b/pkg/loop/internal/core/services/validation/validation.go @@ -18,7 +18,7 @@ type validationServiceClient struct { grpc pb.ValidationServiceClient } -func (v *validationServiceClient) ValidateConfig(ctx context.Context, config map[string]interface{}) error { +func (v *validationServiceClient) ValidateConfig(ctx context.Context, config map[string]any) error { pbConfig, err := structpb.NewStruct(config) if err != nil { return err diff --git a/pkg/loop/internal/net/client.go b/pkg/loop/internal/net/client.go index d15920811f..b009a5eec6 100644 --- a/pkg/loop/internal/net/client.go +++ b/pkg/loop/internal/net/client.go @@ -22,7 +22,7 @@ type AtomicClient struct { func (a *AtomicClient) Store(cc *grpc.ClientConn) { a.cc.Store(cc) } -func (a *AtomicClient) Invoke(ctx context.Context, method string, args interface{}, reply interface{}, opts ...grpc.CallOption) error { +func (a *AtomicClient) Invoke(ctx context.Context, method string, args any, reply any, opts ...grpc.CallOption) error { return a.cc.Load().Invoke(ctx, method, args, reply, opts...) } @@ -48,7 +48,7 @@ type clientConn struct { cc *grpc.ClientConn } -func (c *clientConn) Invoke(ctx context.Context, method string, args interface{}, reply interface{}, opts ...grpc.CallOption) error { +func (c *clientConn) Invoke(ctx context.Context, method string, args any, reply any, opts ...grpc.CallOption) error { c.mu.RLock() cc := c.cc c.mu.RUnlock() diff --git a/pkg/loop/internal/relayer/keystore_bench_test.go b/pkg/loop/internal/relayer/keystore_bench_test.go index 30623fd902..eed6ae7d37 100644 --- a/pkg/loop/internal/relayer/keystore_bench_test.go +++ b/pkg/loop/internal/relayer/keystore_bench_test.go @@ -50,7 +50,7 @@ func BenchmarkKeystore_Sign(b *testing.B) { ctx := tests.Context(b) acct := "0x1234" data := []byte("asdf") - for i := 0; i < b.N; i++ { + for b.Loop() { got, err := ks.Sign(ctx, acct, data) require.NoError(b, err) require.NotEmpty(b, got) @@ -69,7 +69,7 @@ func BenchmarkKeystore_Sign(b *testing.B) { ctx := tests.Context(b) acct := "0x1234" data := []byte("asdf") - for i := 0; i < b.N; i++ { + for b.Loop() { got, err := ks.Sign(ctx, acct, data) require.NoError(b, err) require.NotEmpty(b, got) diff --git a/pkg/loop/internal/relayer/keystore_helper_test.go b/pkg/loop/internal/relayer/keystore_helper_test.go index 24e95e1593..b3f244de6a 100644 --- a/pkg/loop/internal/relayer/keystore_helper_test.go +++ b/pkg/loop/internal/relayer/keystore_helper_test.go @@ -29,7 +29,7 @@ func (p *GRPCPluginKeystore) GRPCServer(broker *plugin.GRPCBroker, server *grpc. return nil } -func (p *GRPCPluginKeystore) GRPCClient(_ context.Context, broker *plugin.GRPCBroker, conn *grpc.ClientConn) (interface{}, error) { +func (p *GRPCPluginKeystore) GRPCClient(_ context.Context, broker *plugin.GRPCBroker, conn *grpc.ClientConn) (any, error) { p.pluginClient = keystore.NewClient(conn) return core.Keystore(p.pluginClient), nil } diff --git a/pkg/loop/internal/relayer/pluginprovider/contractreader/contract_reader.go b/pkg/loop/internal/relayer/pluginprovider/contractreader/contract_reader.go index 4ea4f7bab1..6b86210df8 100644 --- a/pkg/loop/internal/relayer/pluginprovider/contractreader/contract_reader.go +++ b/pkg/loop/internal/relayer/pluginprovider/contractreader/contract_reader.go @@ -668,7 +668,7 @@ func parseBatchGetLatestValuesReply(request types.BatchGetLatestValuesRequest, r return nil, fmt.Errorf("request and results length for contract %s are mismatched %d vs %d", binding, len(requestContractBatch), len(resultsContractBatch)) } - for i := 0; i < len(resultsContractBatch); i++ { + for i := range resultsContractBatch { // type lives in the request, so we can use it for result res, req := resultsContractBatch[i], requestContractBatch[i] if err := codecpb.DecodeVersionedBytes(req.ReturnVal, res.ReturnVal); err != nil { diff --git a/pkg/loop/internal/relayer/pluginprovider/contractreader/contract_reader_test.go b/pkg/loop/internal/relayer/pluginprovider/contractreader/contract_reader_test.go index 34035c9c8d..697d74a44d 100644 --- a/pkg/loop/internal/relayer/pluginprovider/contractreader/contract_reader_test.go +++ b/pkg/loop/internal/relayer/pluginprovider/contractreader/contract_reader_test.go @@ -5,6 +5,7 @@ import ( "errors" "fmt" "iter" + "maps" "math/big" "reflect" "sort" @@ -43,7 +44,7 @@ func TestVersionedBytesFunctions(t *testing.T) { t.Run("EncodeVersionedBytes unsupported encoding version", func(t *testing.T) { expected := fmt.Errorf("%w: unsupported encoding version %d for data map[key:value]", types.ErrInvalidEncoding, unsupportedVer) - data := map[string]interface{}{ + data := map[string]any{ "key": "value", } @@ -54,7 +55,7 @@ func TestVersionedBytesFunctions(t *testing.T) { }) t.Run("DecodeVersionedBytes", func(t *testing.T) { - var decodedData map[string]interface{} + var decodedData map[string]any expected := fmt.Errorf("unsupported encoding version %d for versionedData [97 98 99 100 102]", unsupportedVer) versionedBytes := &codecpb.VersionedBytes{ Version: unsupportedVer, // Unsupported version @@ -68,7 +69,7 @@ func TestVersionedBytesFunctions(t *testing.T) { }) t.Run("DecodeVersionedBytes if nil returns error", func(t *testing.T) { - var decodedData map[string]interface{} + var decodedData map[string]any expected := errors.New("cannot decode nil versioned bytes") err := codecpb.DecodeVersionedBytes(&decodedData, nil) @@ -270,7 +271,7 @@ func TestQueryKey(t *testing.T) { nilTester.Setup(t) nilCr := nilTester.GetContractReader(t) - _, err := nilCr.QueryKey(ctx, types.BoundContract{}, query.KeyFilter{}, query.LimitAndSort{}, &[]interface{}{nil}) + _, err := nilCr.QueryKey(ctx, types.BoundContract{}, query.KeyFilter{}, query.LimitAndSort{}, &[]any{nil}) assert.Equal(t, codes.Unimplemented, status.Convert(err).Code()) }) @@ -278,7 +279,7 @@ func TestQueryKey(t *testing.T) { es.err = errorType t.Run("QueryKey unwraps errors from server "+errorType.Error(), func(t *testing.T) { ctx := t.Context() - _, err := contractReader.QueryKey(ctx, types.BoundContract{}, query.KeyFilter{}, query.LimitAndSort{}, &[]interface{}{nil}) + _, err := contractReader.QueryKey(ctx, types.BoundContract{}, query.KeyFilter{}, query.LimitAndSort{}, &[]any{nil}) assert.True(t, errors.Is(err, errorType)) }) } @@ -288,7 +289,7 @@ func TestQueryKey(t *testing.T) { impl.expectedQueryFilter = tc filter, err := query.Where(tc.Key, tc.Expressions...) require.NoError(t, err) - _, err = cr.QueryKey(t.Context(), types.BoundContract{}, filter, query.LimitAndSort{}, &[]interface{}{nil}) + _, err = cr.QueryKey(t.Context(), types.BoundContract{}, filter, query.LimitAndSort{}, &[]any{nil}) require.NoError(t, err) } }) @@ -533,9 +534,7 @@ func (f *fakeContractReader) SetBatchLatestValues(batchCallEntry BatchCallEntry) f.lock.Lock() defer f.lock.Unlock() f.batchStored = make(BatchCallEntry) - for contractName, contractBatchEntry := range batchCallEntry { - f.batchStored[contractName] = contractBatchEntry - } + maps.Copy(f.batchStored, batchCallEntry) } func (f *fakeContractReader) GetLatestValue(_ context.Context, readIdentifier string, confidenceLevel primitives.ConfidenceLevel, params, returnVal any) error { @@ -671,7 +670,7 @@ func (f *fakeContractReader) BatchGetLatestValues(_ context.Context, request typ storedContractBatch := f.batchStored[requestContract] contractBatchResults := types.ContractBatchResults{} - for i := 0; i < len(requestContractBatch); i++ { + for i := range requestContractBatch { var err error var returnVal any diff --git a/pkg/loop/internal/relayer/pluginprovider/ext/ccip/offramp_test.go b/pkg/loop/internal/relayer/pluginprovider/ext/ccip/offramp_test.go index 19ddd26e45..5f46b602ae 100644 --- a/pkg/loop/internal/relayer/pluginprovider/ext/ccip/offramp_test.go +++ b/pkg/loop/internal/relayer/pluginprovider/ext/ccip/offramp_test.go @@ -60,7 +60,7 @@ func Test_OnchainConfig(t *testing.T) { // lint doesn't like that a proto is copied because it has a mutex for _, tt := range tests { // nolint - tt := tt // nolint + // nolint t.Run(tt.name, func(t *testing.T) { t.Parallel() @@ -131,7 +131,7 @@ func Test_OffchainConfig(t *testing.T) { // lint doesn't like that a proto is copied because it has a mutex for _, tt := range tests { // nolint - tt := tt // nolint + // nolint t.Run(tt.name, func(t *testing.T) { t.Parallel() @@ -195,7 +195,6 @@ func Test_byte32Slice(t *testing.T) { {name: "too short", args: args{pbVal: [][]byte{tooShort}}, ifaceVal: nil, wantErr: true}, } for _, tt := range tests { - tt := tt t.Run(fmt.Sprintf("pb-to-iface %s", tt.name), func(t *testing.T) { t.Parallel() diff --git a/pkg/loop/internal/relayer/pluginprovider/ext/ccip/test/pricegetter.go b/pkg/loop/internal/relayer/pluginprovider/ext/ccip/test/pricegetter.go index a983d6db85..81da70ee78 100644 --- a/pkg/loop/internal/relayer/pluginprovider/ext/ccip/test/pricegetter.go +++ b/pkg/loop/internal/relayer/pluginprovider/ext/ccip/test/pricegetter.go @@ -4,6 +4,7 @@ import ( "context" "fmt" "math/big" + "slices" "github.com/stretchr/testify/assert" @@ -49,12 +50,9 @@ func (s staticPriceGetter) FilterConfiguredTokens(ctx context.Context, tokens [] for _, tk := range tokens { found := false - for _, addr := range s.config.Addresses { - if addr == tk { - found = true - configured = append(configured, tk) - break - } + if slices.Contains(s.config.Addresses, tk) { + found = true + configured = append(configured, tk) } if !found { unconfigured = append(unconfigured, tk) diff --git a/pkg/loop/internal/relayer/pluginprovider/ext/mercury/test/service_fetcher.go b/pkg/loop/internal/relayer/pluginprovider/ext/mercury/test/service_fetcher.go index ba28cd7404..79007fa26a 100644 --- a/pkg/loop/internal/relayer/pluginprovider/ext/mercury/test/service_fetcher.go +++ b/pkg/loop/internal/relayer/pluginprovider/ext/mercury/test/service_fetcher.go @@ -74,16 +74,16 @@ func (s staticServerFetcher) Evaluate(ctx context.Context, other mercury_types.S return nil } -func errMismatch(got, expected interface{}) error { +func errMismatch(got, expected any) error { return errExpected(expected, got) } -func errExpected(expected, got interface{}) error { +func errExpected(expected, got any) error { return &ErrExpected{expected, got} } type ErrExpected struct { - Expected, Got interface{} + Expected, Got any } func (e *ErrExpected) Error() string { diff --git a/pkg/loop/internal/test/cmd/main.go b/pkg/loop/internal/test/cmd/main.go index 1f9c7d8cd3..59dba05c4f 100644 --- a/pkg/loop/internal/test/cmd/main.go +++ b/pkg/loop/internal/test/cmd/main.go @@ -235,7 +235,7 @@ func main() { func limitInterceptors(limit int) (grpc.UnaryServerInterceptor, grpc.StreamServerInterceptor) { count := make(chan struct{}) go func() { - for i := 0; i < limit; i++ { + for range limit { <-count } os.Exit(3) @@ -243,15 +243,15 @@ func limitInterceptors(limit int) (grpc.UnaryServerInterceptor, grpc.StreamServe return limitUnaryInterceptor(count), limitStreamInterceptor(count) } -func limitUnaryInterceptor(count chan<- struct{}) func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) { - return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) { +func limitUnaryInterceptor(count chan<- struct{}) func(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp any, err error) { + return func(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp any, err error) { count <- struct{}{} return handler(ctx, req) } } -func limitStreamInterceptor(count chan<- struct{}) func(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { - return func(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { +func limitStreamInterceptor(count chan<- struct{}) func(srv any, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { + return func(srv any, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error { count <- struct{}{} return handler(srv, ss) } diff --git a/pkg/loop/internal/test/logger_loop.go b/pkg/loop/internal/test/logger_loop.go index 2e53ca5039..485ae80b01 100644 --- a/pkg/loop/internal/test/logger_loop.go +++ b/pkg/loop/internal/test/logger_loop.go @@ -57,7 +57,7 @@ func (g *GRPCPluginLoggerTest) GRPCServer(*plugin.GRPCBroker, *grpc.Server) (err return err } -func (g *GRPCPluginLoggerTest) GRPCClient(context.Context, *plugin.GRPCBroker, *grpc.ClientConn) (interface{}, error) { +func (g *GRPCPluginLoggerTest) GRPCClient(context.Context, *plugin.GRPCBroker, *grpc.ClientConn) (any, error) { return nil, errors.New("unimplemented") } diff --git a/pkg/loop/logger.go b/pkg/loop/logger.go index 848d92341d..ec0842b838 100644 --- a/pkg/loop/logger.go +++ b/pkg/loop/logger.go @@ -44,7 +44,7 @@ func (h *hclSinkAdapter) named(name string) logger.SugaredLogger { return v.(func() logger.SugaredLogger)() } -func removeArg(args []interface{}, key string) ([]interface{}, string) { +func removeArg(args []any, key string) ([]any, string) { if len(args) < 2 { return args, "" } @@ -69,13 +69,13 @@ type logMessage struct { // LogMessageExtraArgs is a key value pair within the Output payload type LogMessageExtraArgs struct { - Key string `json:"key"` - Value interface{} `json:"value"` + Key string `json:"key"` + Value any `json:"value"` } // flattenExtraArgs is used to flatten arguments of the log message -func flattenExtraArgs(le *logMessage) []interface{} { - var result []interface{} +func flattenExtraArgs(le *logMessage) []any { + var result []any result = append(result, "level") result = append(result, le.Level) result = append(result, "timestamp") @@ -89,7 +89,7 @@ func flattenExtraArgs(le *logMessage) []interface{} { } func parseJSON(input string) (*logMessage, error) { - var raw map[string]interface{} + var raw map[string]any entry := &logMessage{} err := json.Unmarshal([]byte(input), &raw) @@ -119,7 +119,7 @@ func parseJSON(input string) (*logMessage, error) { // logDebug will parse msg and figure out if it's a panic, fatal or critical log message, this is done here because the hashicorp plugin will push any // unrecognizable message from stderr as a debug statement -func logDebug(msg string, l logger.SugaredLogger, args ...interface{}) { +func logDebug(msg string, l logger.SugaredLogger, args ...any) { if strings.HasPrefix(msg, "panic:") { l.Criticalw(fmt.Sprintf("[PANIC] %s", msg), args...) } else if log, err := parseJSON(msg); err == nil { @@ -136,7 +136,7 @@ func logDebug(msg string, l logger.SugaredLogger, args ...interface{}) { } } -func (h *hclSinkAdapter) Accept(_ string, level hclog.Level, msg string, args ...interface{}) { +func (h *hclSinkAdapter) Accept(_ string, level hclog.Level, msg string, args ...any) { if level == hclog.Off { return } diff --git a/pkg/loop/logger_test.go b/pkg/loop/logger_test.go index 731f97b46b..1929ba85bf 100644 --- a/pkg/loop/logger_test.go +++ b/pkg/loop/logger_test.go @@ -15,10 +15,10 @@ import ( func Test_removeArg(t *testing.T) { for _, tt := range []struct { name string - args []interface{} + args []any key string - wantArgs []interface{} + wantArgs []any wantVal string }{ {"empty", nil, "logger", diff --git a/pkg/loop/plugin_keystore.go b/pkg/loop/plugin_keystore.go index 0ad9421c08..f042413d0a 100644 --- a/pkg/loop/plugin_keystore.go +++ b/pkg/loop/plugin_keystore.go @@ -34,7 +34,7 @@ func (p *GRPCPluginKeystore) GRPCServer(broker *plugin.GRPCBroker, server *grpc. return keystorepb.RegisterKeystoreServer(server, broker, p.BrokerConfig, p.PluginServer) } -func (p *GRPCPluginKeystore) GRPCClient(_ context.Context, broker *plugin.GRPCBroker, conn *grpc.ClientConn) (interface{}, error) { +func (p *GRPCPluginKeystore) GRPCClient(_ context.Context, broker *plugin.GRPCBroker, conn *grpc.ClientConn) (any, error) { if p.pluginClient == nil { p.pluginClient = keystorepb.NewKeystoreClient(p.BrokerConfig) } diff --git a/pkg/loop/plugin_median.go b/pkg/loop/plugin_median.go index 6bae70e320..e7052b39cf 100644 --- a/pkg/loop/plugin_median.go +++ b/pkg/loop/plugin_median.go @@ -45,7 +45,7 @@ func (p *GRPCPluginMedian) GRPCServer(broker *plugin.GRPCBroker, server *grpc.Se } // GRPCClient implements [plugin.GRPCPlugin] and returns the pluginClient [types.PluginMedian], updated with the new broker and conn. -func (p *GRPCPluginMedian) GRPCClient(_ context.Context, broker *plugin.GRPCBroker, conn *grpc.ClientConn) (interface{}, error) { +func (p *GRPCPluginMedian) GRPCClient(_ context.Context, broker *plugin.GRPCBroker, conn *grpc.ClientConn) (any, error) { if p.pluginClient == nil { p.pluginClient = median.NewPluginMedianClient(p.BrokerConfig) } diff --git a/pkg/loop/plugin_mercury.go b/pkg/loop/plugin_mercury.go index 288a086862..3090d02b9c 100644 --- a/pkg/loop/plugin_mercury.go +++ b/pkg/loop/plugin_mercury.go @@ -35,7 +35,7 @@ func (p *GRPCPluginMercury) GRPCServer(broker *plugin.GRPCBroker, server *grpc.S } // GRPCClient implements [plugin.GRPCPlugin] and returns the pluginClient [types.PluginMercury], updated with the new broker and conn. -func (p *GRPCPluginMercury) GRPCClient(_ context.Context, broker *plugin.GRPCBroker, conn *grpc.ClientConn) (interface{}, error) { +func (p *GRPCPluginMercury) GRPCClient(_ context.Context, broker *plugin.GRPCBroker, conn *grpc.ClientConn) (any, error) { if p.pluginClient == nil { p.pluginClient = mercury.NewMercuryAdapterClient(p.BrokerConfig) } diff --git a/pkg/loop/plugin_relayer.go b/pkg/loop/plugin_relayer.go index b780bd7aee..0e87835432 100644 --- a/pkg/loop/plugin_relayer.go +++ b/pkg/loop/plugin_relayer.go @@ -50,7 +50,7 @@ func (p *GRPCPluginRelayer) GRPCServer(broker *plugin.GRPCBroker, server *grpc.S // GRPCClient implements [plugin.GRPCPlugin] and returns the pluginClient [types.PluginRelayer], updated with the new broker and conn. -func (p *GRPCPluginRelayer) GRPCClient(_ context.Context, broker *plugin.GRPCBroker, conn *grpc.ClientConn) (interface{}, error) { +func (p *GRPCPluginRelayer) GRPCClient(_ context.Context, broker *plugin.GRPCBroker, conn *grpc.ClientConn) (any, error) { if p.pluginClient == nil { p.pluginClient = relayer.NewPluginRelayerClient(p.BrokerConfig) } diff --git a/pkg/loop/reportingplugins/grpc.go b/pkg/loop/reportingplugins/grpc.go index 6421733258..172ee12d26 100644 --- a/pkg/loop/reportingplugins/grpc.go +++ b/pkg/loop/reportingplugins/grpc.go @@ -105,7 +105,7 @@ func (g *GRPCService[T]) GRPCServer(broker *plugin.GRPCBroker, server *grpc.Serv } // GRPCClient implements [plugin.GRPCPlugin] and returns the pluginClient [types.PluginClient], updated with the new broker and conn. -func (g *GRPCService[T]) GRPCClient(_ context.Context, broker *plugin.GRPCBroker, conn *grpc.ClientConn) (interface{}, error) { +func (g *GRPCService[T]) GRPCClient(_ context.Context, broker *plugin.GRPCBroker, conn *grpc.ClientConn) (any, error) { if g.pluginClient == nil { g.pluginClient = ocr2.NewReportingPluginServiceClient(g.BrokerConfig) } diff --git a/pkg/loop/reportingplugins/loopp_service.go b/pkg/loop/reportingplugins/loopp_service.go index 4c43cdace8..264374e7d5 100644 --- a/pkg/loop/reportingplugins/loopp_service.go +++ b/pkg/loop/reportingplugins/loopp_service.go @@ -95,7 +95,7 @@ func NewLOOPPServiceValidation( return &ps } -func (g *LOOPPServiceValidation) ValidateConfig(ctx context.Context, config map[string]interface{}) error { +func (g *LOOPPServiceValidation) ValidateConfig(ctx context.Context, config map[string]any) error { if err := g.WaitCtx(ctx); err != nil { return err } diff --git a/pkg/loop/reportingplugins/ocr3/grpc.go b/pkg/loop/reportingplugins/ocr3/grpc.go index 54907437b4..8bb18dd6bf 100644 --- a/pkg/loop/reportingplugins/ocr3/grpc.go +++ b/pkg/loop/reportingplugins/ocr3/grpc.go @@ -95,7 +95,7 @@ func (g *GRPCService[T]) GRPCServer(broker *plugin.GRPCBroker, server *grpc.Serv }) } -func (g *GRPCService[T]) GRPCClient(_ context.Context, broker *plugin.GRPCBroker, conn *grpc.ClientConn) (interface{}, error) { +func (g *GRPCService[T]) GRPCClient(_ context.Context, broker *plugin.GRPCBroker, conn *grpc.ClientConn) (any, error) { if g.pluginClient == nil { g.pluginClient = ocr3.NewReportingPluginServiceClient(g.BrokerConfig) } diff --git a/pkg/loop/standard_capabilities.go b/pkg/loop/standard_capabilities.go index 67e34f09ff..f5021ea9c0 100644 --- a/pkg/loop/standard_capabilities.go +++ b/pkg/loop/standard_capabilities.go @@ -37,7 +37,7 @@ func (p *StandardCapabilitiesLoop) GRPCServer(broker *plugin.GRPCBroker, server return standardcapability.RegisterStandardCapabilitiesServer(server, broker, p.BrokerConfig, p.PluginServer) } -func (p *StandardCapabilitiesLoop) GRPCClient(_ context.Context, broker *plugin.GRPCBroker, conn *grpc.ClientConn) (interface{}, error) { +func (p *StandardCapabilitiesLoop) GRPCClient(_ context.Context, broker *plugin.GRPCBroker, conn *grpc.ClientConn) (any, error) { if p.pluginClient == nil { p.pluginClient = standardcapability.NewStandardCapabilitiesClient(p.BrokerConfig) } diff --git a/pkg/merklemulti/merkle_multi.go b/pkg/merklemulti/merkle_multi.go index fb95d8d87d..92bfa72dd7 100644 --- a/pkg/merklemulti/merkle_multi.go +++ b/pkg/merklemulti/merkle_multi.go @@ -168,7 +168,7 @@ func VerifyComputeRoot[H hashutil.Hash](hasher hashutil.Hasher[H], leafHashes [] return hasher.ZeroHash(), fmt.Errorf("proof source flags %d != proof hashes %d", sourceProofCount, proofsLength) } hashes := make([]H, totalHashes) - for i := 0; i < totalHashes; i++ { + for range totalHashes { hashes = append(hashes, leafHashes[0]) } var ( @@ -176,7 +176,7 @@ func VerifyComputeRoot[H hashutil.Hash](hasher hashutil.Hasher[H], leafHashes [] hashPos int proofPos int ) - for i := 0; i < totalHashes; i++ { + for i := range totalHashes { var a, b H //nolint:gosimple if proof.SourceFlags[i] == SourceFromHashes { diff --git a/pkg/metrics/metrics_labeler.go b/pkg/metrics/metrics_labeler.go index ade67d7807..664ddfdb7c 100644 --- a/pkg/metrics/metrics_labeler.go +++ b/pkg/metrics/metrics_labeler.go @@ -1,5 +1,7 @@ package metrics +import "maps" + type Labeler struct { Labels map[string]string } @@ -18,9 +20,7 @@ func (c Labeler) With(keyValues ...string) Labeler { } // Copy existing labels from the current agent - for k, v := range c.Labels { - newCustomMetricsLabeler.Labels[k] = v - } + maps.Copy(newCustomMetricsLabeler.Labels, c.Labels) // Add new key-value pairs for i := 0; i < len(keyValues); i += 2 { diff --git a/pkg/nodeauth/jwt/node_jwt_authenticator.go b/pkg/nodeauth/jwt/node_jwt_authenticator.go index 06e5c954ac..f91c4628b0 100644 --- a/pkg/nodeauth/jwt/node_jwt_authenticator.go +++ b/pkg/nodeauth/jwt/node_jwt_authenticator.go @@ -99,7 +99,7 @@ func (v *NodeJWTAuthenticator) parseJWTClaims(tokenString string) (*types.NodeJW // verifyJWTSignature prove the JWT signature is signed by the node's private key. func (v *NodeJWTAuthenticator) verifyJWTSignature(tokenString string, publicKey ed25519.PublicKey) error { - token, err := v.parser.Parse(tokenString, func(token *jwt.Token) (interface{}, error) { + token, err := v.parser.Parse(tokenString, func(token *jwt.Token) (any, error) { // Ensure the signing method is jwt.SigningMethodEd25519 if _, ok := token.Method.(*jwt.SigningMethodEd25519); !ok { return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"]) diff --git a/pkg/nodeauth/jwt/node_jwt_generator_test.go b/pkg/nodeauth/jwt/node_jwt_generator_test.go index 55e848755a..b652b5d35c 100644 --- a/pkg/nodeauth/jwt/node_jwt_generator_test.go +++ b/pkg/nodeauth/jwt/node_jwt_generator_test.go @@ -126,7 +126,7 @@ func TestNodeJWTGenerator_ValidateSignature(t *testing.T) { require.NoError(t, err) // Parse and validate the JWT token with signature verification - token, err := jwt.ParseWithClaims(jwtToken, &types.NodeJWTClaims{}, func(token *jwt.Token) (interface{}, error) { + token, err := jwt.ParseWithClaims(jwtToken, &types.NodeJWTClaims{}, func(token *jwt.Token) (any, error) { // Ensure the signing method is EdDSA if _, ok := token.Method.(*jwt.SigningMethodEd25519); !ok { return nil, assert.AnError diff --git a/pkg/nodeauth/utils/utils.go b/pkg/nodeauth/utils/utils.go index 6568569aad..3ad289d20b 100644 --- a/pkg/nodeauth/utils/utils.go +++ b/pkg/nodeauth/utils/utils.go @@ -21,12 +21,12 @@ func CalculateRequestDigest(req any) string { data = serialized } else { // fallback to string representation if marshal fails - data = []byte(fmt.Sprintf("%v", req)) + data = fmt.Appendf(nil, "%v", req) } } else if s, ok := req.(fmt.Stringer); ok { data = []byte(s.String()) } else { - data = []byte(fmt.Sprintf("%v", req)) + data = fmt.Appendf(nil, "%v", req) } hash := sha256.Sum256(data) diff --git a/pkg/services/servicetest/run_test.go b/pkg/services/servicetest/run_test.go index 0d47fd5fc9..ff73c45811 100644 --- a/pkg/services/servicetest/run_test.go +++ b/pkg/services/servicetest/run_test.go @@ -69,7 +69,7 @@ func (f *fakeTest) Cleanup(fn func()) { f.cleanup = append(f.cleanup, fn) } -func (f *fakeTest) Errorf(format string, args ...interface{}) { +func (f *fakeTest) Errorf(format string, args ...any) { f.errors = append(f.errors, fmt.Sprintf(format, args...)) f.failed = true } diff --git a/pkg/settings/limits/bound.go b/pkg/settings/limits/bound.go index f10c5b0daf..e2cee9cc69 100644 --- a/pkg/settings/limits/bound.go +++ b/pkg/settings/limits/bound.go @@ -136,7 +136,7 @@ func (b *boundLimiter[N]) Close() (err error) { if b.scope == settings.ScopeGlobal { return b.updater.Close() } else { - b.updaters.Range(func(key, value interface{}) bool { + b.updaters.Range(func(key, value any) bool { // opt: parallelize err = errors.Join(err, value.(*updater[N]).Close()) return true diff --git a/pkg/settings/limits/queue.go b/pkg/settings/limits/queue.go index 48e727f34f..7ccf23ed97 100644 --- a/pkg/settings/limits/queue.go +++ b/pkg/settings/limits/queue.go @@ -269,7 +269,7 @@ func (s *scopedQueue[T]) Close() (err error) { s.wg.Wait() // cleanup - s.queues.Range(func(tenant, value interface{}) bool { + s.queues.Range(func(tenant, value any) bool { // opt: parallelize err = errors.Join(err, value.(*queue[T]).Close()) return true diff --git a/pkg/settings/limits/rate.go b/pkg/settings/limits/rate.go index c3c82f522d..92541570fe 100644 --- a/pkg/settings/limits/rate.go +++ b/pkg/settings/limits/rate.go @@ -393,7 +393,7 @@ func (s *scopedRateLimiter) Close() (err error) { s.wg.Wait() // cleanup - s.limiters.Range(func(tenant, value interface{}) bool { + s.limiters.Range(func(tenant, value any) bool { // opt: parallelize err = errors.Join(err, value.(*rateLimiter).Close()) return true diff --git a/pkg/settings/limits/resource.go b/pkg/settings/limits/resource.go index 47cd1f1507..75e716e80f 100644 --- a/pkg/settings/limits/resource.go +++ b/pkg/settings/limits/resource.go @@ -241,7 +241,7 @@ func (u *resourcePoolUsage[N]) available(ctx context.Context) (N, error) { return limit - u.used, nil } -//opt: queue instead of racing for the [sync.Mutex] & [sync.Cond] +// opt: queue instead of racing for the [sync.Mutex] & [sync.Cond] func (u *resourcePoolUsage[N]) use(ctx context.Context, amount N, block bool) error { limit, err := u.get(ctx) if err != nil { @@ -468,7 +468,7 @@ func (s *scopedResourcePoolLimiter[N]) Close() (err error) { s.wg.Wait() // cleanup - s.used.Range(func(tenant, value interface{}) bool { + s.used.Range(func(tenant, value any) bool { // opt: parallelize err = errors.Join(err, value.(*resourcePoolUsage[N]).Close()) return true diff --git a/pkg/settings/limits/time.go b/pkg/settings/limits/time.go index abe72f6206..3d9f01930b 100644 --- a/pkg/settings/limits/time.go +++ b/pkg/settings/limits/time.go @@ -124,7 +124,7 @@ func (l *timeLimiter) Close() (err error) { if l.scope == settings.ScopeGlobal { return l.updater.Close() } else { - l.updaters.Range(func(key, value interface{}) bool { + l.updaters.Range(func(key, value any) bool { // opt: parallelize err = errors.Join(err, value.(*updater[time.Duration]).Close()) return true diff --git a/pkg/settings/settings.go b/pkg/settings/settings.go index 675c344def..29e78d0508 100644 --- a/pkg/settings/settings.go +++ b/pkg/settings/settings.go @@ -41,7 +41,7 @@ type Setting[T any] struct { } func (s Setting[T]) MarshalText() ([]byte, error) { - return []byte(fmt.Sprintf("%v", s.DefaultValue)), nil + return fmt.Appendf(nil, "%v", s.DefaultValue), nil } func (s *Setting[T]) UnmarshalText(b []byte) (err error) { diff --git a/pkg/sqlutil/hook.go b/pkg/sqlutil/hook.go index cff7a78c05..da84e2f12b 100644 --- a/pkg/sqlutil/hook.go +++ b/pkg/sqlutil/hook.go @@ -77,7 +77,7 @@ func (w *wrappedDataSource) Rebind(s string) string { return w.db.Rebind(s) } -func (w *wrappedDataSource) BindNamed(s string, i interface{}) (string, []any, error) { +func (w *wrappedDataSource) BindNamed(s string, i any) (string, []any, error) { return w.db.BindNamed(s, i) } @@ -119,7 +119,7 @@ func (w *wrappedDataSource) ExecContext(ctx context.Context, query string, args return } -func (w *wrappedDataSource) NamedExecContext(ctx context.Context, query string, arg interface{}) (res sql.Result, err error) { +func (w *wrappedDataSource) NamedExecContext(ctx context.Context, query string, arg any) (res sql.Result, err error) { err = w.hook(ctx, w.lggr, func(ctx context.Context) (err error) { res, err = w.db.NamedExecContext(ctx, query, arg) return @@ -143,13 +143,13 @@ func (w *wrappedDataSource) PrepareNamedContext(ctx context.Context, query strin return } -func (w *wrappedDataSource) GetContext(ctx context.Context, dest interface{}, query string, args ...any) error { +func (w *wrappedDataSource) GetContext(ctx context.Context, dest any, query string, args ...any) error { return w.hook(ctx, w.lggr, func(ctx context.Context) error { return w.db.GetContext(ctx, dest, query, args...) }, query, args...) } -func (w *wrappedDataSource) SelectContext(ctx context.Context, dest interface{}, query string, args ...any) error { +func (w *wrappedDataSource) SelectContext(ctx context.Context, dest any, query string, args ...any) error { return w.hook(ctx, w.lggr, func(ctx context.Context) error { return w.db.SelectContext(ctx, dest, query, args...) }, query, args...) diff --git a/pkg/sqlutil/hook_test.go b/pkg/sqlutil/hook_test.go index 1be8726cc2..a95e59e2fd 100644 --- a/pkg/sqlutil/hook_test.go +++ b/pkg/sqlutil/hook_test.go @@ -110,27 +110,27 @@ func (q *dataSource) DriverName() string { return "" } func (q *dataSource) Rebind(s string) string { return "" } -func (q *dataSource) BindNamed(s string, i interface{}) (string, []interface{}, error) { +func (q *dataSource) BindNamed(s string, i any) (string, []any, error) { return "", nil, nil } -func (q *dataSource) QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error) { +func (q *dataSource) QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error) { return nil, nil } -func (q *dataSource) QueryxContext(ctx context.Context, query string, args ...interface{}) (*sqlx.Rows, error) { +func (q *dataSource) QueryxContext(ctx context.Context, query string, args ...any) (*sqlx.Rows, error) { return nil, nil } -func (q *dataSource) QueryRowxContext(ctx context.Context, query string, args ...interface{}) *sqlx.Row { +func (q *dataSource) QueryRowxContext(ctx context.Context, query string, args ...any) *sqlx.Row { return nil } -func (q *dataSource) ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error) { +func (q *dataSource) ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error) { return nil, nil } -func (q *dataSource) NamedExecContext(ctx context.Context, query string, arg interface{}) (sql.Result, error) { +func (q *dataSource) NamedExecContext(ctx context.Context, query string, arg any) (sql.Result, error) { return nil, nil } @@ -142,7 +142,7 @@ func (q *dataSource) PrepareNamedContext(ctx context.Context, query string) (*sq return nil, nil } -func (q *dataSource) GetContext(ctx context.Context, dest interface{}, query string, args ...interface{}) error { +func (q *dataSource) GetContext(ctx context.Context, dest any, query string, args ...any) error { select { case <-ctx.Done(): return ctx.Err() @@ -151,7 +151,7 @@ func (q *dataSource) GetContext(ctx context.Context, dest interface{}, query str return nil } -func (q *dataSource) SelectContext(ctx context.Context, dest interface{}, query string, args ...interface{}) error { +func (q *dataSource) SelectContext(ctx context.Context, dest any, query string, args ...any) error { select { case <-ctx.Done(): return ctx.Err() diff --git a/pkg/sqlutil/interval.go b/pkg/sqlutil/interval.go index 1491b2986b..b5d79fb857 100644 --- a/pkg/sqlutil/interval.go +++ b/pkg/sqlutil/interval.go @@ -35,7 +35,7 @@ func (i *Interval) UnmarshalText(input []byte) error { return nil } -func (i *Interval) Scan(v interface{}) error { +func (i *Interval) Scan(v any) error { if v == nil { *i = Interval(time.Duration(0)) return nil diff --git a/pkg/sqlutil/json.go b/pkg/sqlutil/json.go index 44b4dcb713..238fe4bb2e 100644 --- a/pkg/sqlutil/json.go +++ b/pkg/sqlutil/json.go @@ -19,7 +19,7 @@ func (j JSON) Value() (driver.Value, error) { } // Scan scan value into Jsonb, implements sql.Scanner interface -func (j *JSON) Scan(value interface{}) error { +func (j *JSON) Scan(value any) error { if value == nil { *j = JSON("null") return nil diff --git a/pkg/sqlutil/monitor.go b/pkg/sqlutil/monitor.go index 6a989ef972..36104308bb 100644 --- a/pkg/sqlutil/monitor.go +++ b/pkg/sqlutil/monitor.go @@ -45,7 +45,7 @@ func MonitorHook(logAll func() bool) QueryHook { } // sprintQ formats the query with the given args and returns the resulting string. -func sprintQ(query string, args []interface{}) string { +func sprintQ(query string, args []any) string { if args == nil { return query } @@ -88,7 +88,7 @@ type queryLogger struct { lggr logger.SugaredLogger query string - args []interface{} + args []any str func() string } diff --git a/pkg/sqlutil/monitor_test.go b/pkg/sqlutil/monitor_test.go index cb0ec5336e..e917739dfa 100644 --- a/pkg/sqlutil/monitor_test.go +++ b/pkg/sqlutil/monitor_test.go @@ -19,7 +19,7 @@ func Test_sprintQ(t *testing.T) { for _, tt := range []struct { name string query string - args []interface{} + args []any exp string }{ {"none", @@ -28,27 +28,27 @@ func Test_sprintQ(t *testing.T) { "SELECT * FROM table;"}, {"one", "SELECT $1 FROM table;", - []interface{}{"foo"}, + []any{"foo"}, "SELECT 'foo' FROM table;"}, {"two", "SELECT $1 FROM table WHERE bar = $2;", - []interface{}{"foo", 1}, + []any{"foo", 1}, "SELECT 'foo' FROM table WHERE bar = 1;"}, {"limit", "SELECT $1 FROM table LIMIT $2;", - []interface{}{"foo", limit(10)}, + []any{"foo", limit(10)}, "SELECT 'foo' FROM table LIMIT 10;"}, {"limit-all", "SELECT $1 FROM table LIMIT $2;", - []interface{}{"foo", limit(-1)}, + []any{"foo", limit(-1)}, "SELECT 'foo' FROM table LIMIT NULL;"}, {"bytea", "SELECT $1 FROM table WHERE b = $2;", - []interface{}{"foo", []byte{0x0a}}, + []any{"foo", []byte{0x0a}}, "SELECT 'foo' FROM table WHERE b = '\\x0a';"}, {"bytea[]", "SELECT $1 FROM table WHERE b = $2;", - []interface{}{"foo", pq.ByteaArray([][]byte{{0xa}, {0xb}})}, + []any{"foo", pq.ByteaArray([][]byte{{0xa}, {0xb}})}, "SELECT 'foo' FROM table WHERE b = ARRAY['\\x0a','\\x0b'];"}, } { t.Run(tt.name, func(t *testing.T) { diff --git a/pkg/sqlutil/sqltest/data_source.go b/pkg/sqlutil/sqltest/data_source.go index 4c37e68ab3..3e1e284821 100644 --- a/pkg/sqlutil/sqltest/data_source.go +++ b/pkg/sqlutil/sqltest/data_source.go @@ -27,7 +27,7 @@ func NewNoOpDataSource() sqlutil.DataSource { type noOpDataSource struct{} -func (ds *noOpDataSource) BindNamed(s string, _ interface{}) (string, []interface{}, error) { +func (ds *noOpDataSource) BindNamed(s string, _ any) (string, []any, error) { return "", nil, nil } @@ -35,15 +35,15 @@ func (ds *noOpDataSource) DriverName() string { return "" } -func (ds *noOpDataSource) ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error) { +func (ds *noOpDataSource) ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error) { return nil, nil } -func (ds *noOpDataSource) GetContext(ctx context.Context, dest interface{}, query string, args ...interface{}) error { +func (ds *noOpDataSource) GetContext(ctx context.Context, dest any, query string, args ...any) error { return nil } -func (ds *noOpDataSource) NamedExecContext(ctx context.Context, query string, arg interface{}) (sql.Result, error) { +func (ds *noOpDataSource) NamedExecContext(ctx context.Context, query string, arg any) (sql.Result, error) { return nil, nil } @@ -55,15 +55,15 @@ func (_m *noOpDataSource) PrepareNamedContext(ctx context.Context, query string) return nil, nil } -func (ds *noOpDataSource) QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error) { +func (ds *noOpDataSource) QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error) { return nil, nil } -func (ds *noOpDataSource) QueryRowxContext(ctx context.Context, query string, args ...interface{}) *sqlx.Row { +func (ds *noOpDataSource) QueryRowxContext(ctx context.Context, query string, args ...any) *sqlx.Row { return nil } -func (ds *noOpDataSource) QueryxContext(ctx context.Context, query string, args ...interface{}) (*sqlx.Rows, error) { +func (ds *noOpDataSource) QueryxContext(ctx context.Context, query string, args ...any) (*sqlx.Rows, error) { return nil, nil } @@ -71,6 +71,6 @@ func (ds *noOpDataSource) Rebind(s string) string { return "" } -func (ds *noOpDataSource) SelectContext(ctx context.Context, dest interface{}, query string, args ...interface{}) error { +func (ds *noOpDataSource) SelectContext(ctx context.Context, dest any, query string, args ...any) error { return nil } diff --git a/pkg/sqlutil/sqltest/sqltest.go b/pkg/sqlutil/sqltest/sqltest.go index 3ca4eeefb6..ecf023784d 100644 --- a/pkg/sqlutil/sqltest/sqltest.go +++ b/pkg/sqlutil/sqltest/sqltest.go @@ -91,7 +91,7 @@ func CreateOrReplace(t testing.TB, u url.URL, dbName string, template string) ur t.Cleanup(func() { var err error attempts := 10 - for i := 0; i < attempts; i++ { + for range attempts { err = drop(u) if err == nil { return diff --git a/pkg/sqlutil/sqltest/txdb.go b/pkg/sqlutil/sqltest/txdb.go index 68a29ed706..39441d495f 100644 --- a/pkg/sqlutil/sqltest/txdb.go +++ b/pkg/sqlutil/sqltest/txdb.go @@ -8,6 +8,7 @@ import ( "fmt" "io" "net/url" + "slices" "strings" "sync" @@ -38,11 +39,9 @@ func RegisterTxDB(dbURL string) error { defer registerMutex.Unlock() drivers := sql.Drivers() - for _, driver := range drivers { - if driver == pg.DriverTxWrappedPostgres { - // TxDB driver already registered - return nil - } + if slices.Contains(drivers, pg.DriverTxWrappedPostgres) { + // TxDB driver already registered + return nil } if dbURL != pg.DriverInMemoryPostgres { @@ -365,8 +364,8 @@ func (s *stmt) ExecContext(_ context.Context, args []driver.NamedValue) (driver. return s.st.ExecContext(ctx, mapNamedArgs(args)...) } -func mapArgs(args []driver.Value) (res []interface{}) { - res = make([]interface{}, len(args)) +func mapArgs(args []driver.Value) (res []any) { + res = make([]any, len(args)) for i := range args { res[i] = args[i] } @@ -471,7 +470,7 @@ func (r *rows) Next(dest []driver.Value) error { } for i, val := range r.rows[r.pos-1] { - dest[i] = *(val.(*interface{})) + dest[i] = *(val.(*any)) } return nil @@ -494,9 +493,9 @@ func (r *rows) read(rs *sql.Rows) error { } for rs.Next() { - values := make([]interface{}, len(r.cols)) + values := make([]any, len(r.cols)) for i := range values { - values[i] = new(interface{}) + values[i] = new(any) } if err := rs.Scan(values...); err != nil { return err @@ -532,8 +531,8 @@ func (rs *rowSets) Next(dest []driver.Value) error { return rs.sets[rs.pos].Next(dest) } -func mapNamedArgs(args []driver.NamedValue) (res []interface{}) { - res = make([]interface{}, len(args)) +func mapNamedArgs(args []driver.NamedValue) (res []any) { + res = make([]any, len(args)) for i := range args { name := args[i].Name if name != "" { diff --git a/pkg/sqlutil/sqltest/txdb_test.go b/pkg/sqlutil/sqltest/txdb_test.go index f9fedd31f8..9adb3fc3fa 100644 --- a/pkg/sqlutil/sqltest/txdb_test.go +++ b/pkg/sqlutil/sqltest/txdb_test.go @@ -21,7 +21,7 @@ func TestTxDBDriver(t *testing.T) { t.Run("Make sure sql.Register() can be called concurrently without racing", func(t *testing.T) { wg := sync.WaitGroup{} - for i := 0; i < 10; i++ { + for range 10 { wg.Add(1) go func() { err := RegisterTxDB(pg.DriverInMemoryPostgres) diff --git a/pkg/sqlutil/sqlutil.go b/pkg/sqlutil/sqlutil.go index 4e956a404e..a91dc2956b 100644 --- a/pkg/sqlutil/sqlutil.go +++ b/pkg/sqlutil/sqlutil.go @@ -18,17 +18,17 @@ var _ DataSource = (*sqlx.Tx)(nil) type DataSource interface { sqlx.ExtContext sqlx.PreparerContext - GetContext(ctx context.Context, dest interface{}, query string, args ...interface{}) error - SelectContext(ctx context.Context, dest interface{}, query string, args ...interface{}) error + GetContext(ctx context.Context, dest any, query string, args ...any) error + SelectContext(ctx context.Context, dest any, query string, args ...any) error PrepareNamedContext(ctx context.Context, query string) (*sqlx.NamedStmt, error) - NamedExecContext(ctx context.Context, query string, arg interface{}) (sql.Result, error) + NamedExecContext(ctx context.Context, query string, arg any) (sql.Result, error) } type RowScanner interface { Scan(dest ...any) error - SliceScan() ([]interface{}, error) - MapScan(dest map[string]interface{}) error - StructScan(dest interface{}) error + SliceScan() ([]any, error) + MapScan(dest map[string]any) error + StructScan(dest any) error } // NamedQueryContext is like sqlx.NamedQueryContext, but it works with any DataSource. diff --git a/pkg/timeutil/jitter_test.go b/pkg/timeutil/jitter_test.go index 2517449672..164a1bc17a 100644 --- a/pkg/timeutil/jitter_test.go +++ b/pkg/timeutil/jitter_test.go @@ -17,7 +17,7 @@ func TestJitterPct(t *testing.T) { {0.1, 24 * time.Hour, 21*time.Hour + 36*time.Minute, 26*time.Hour + 24*time.Minute}, } { t.Run(tt.dur.String(), func(t *testing.T) { - for i := 0; i < 100; i++ { + for i := range 100 { got := tt.pct.Apply(tt.dur) t.Logf("%d: %s", i, got) if got < tt.from || got > tt.to { diff --git a/pkg/types/automation/basetypes.go b/pkg/types/automation/basetypes.go index 96013c95fe..da69737ab9 100644 --- a/pkg/types/automation/basetypes.go +++ b/pkg/types/automation/basetypes.go @@ -178,10 +178,10 @@ func (r CheckResult) UniqueID() string { resultBytes = append(resultBytes, r.PipelineExecutionState) resultBytes = append(resultBytes, checkResultDelimiter) - resultBytes = append(resultBytes, []byte(fmt.Sprintf("%+v", r.Retryable))...) + resultBytes = append(resultBytes, fmt.Appendf(nil, "%+v", r.Retryable)...) resultBytes = append(resultBytes, checkResultDelimiter) - resultBytes = append(resultBytes, []byte(fmt.Sprintf("%+v", r.Eligible))...) + resultBytes = append(resultBytes, fmt.Appendf(nil, "%+v", r.Eligible)...) resultBytes = append(resultBytes, checkResultDelimiter) resultBytes = append(resultBytes, r.IneligibilityReason) @@ -200,7 +200,7 @@ func (r CheckResult) UniqueID() string { // Note: We encode the whole trigger extension so the behaiour of // LogTriggerExtentsion.BlockNumber and LogTriggerExtentsion.BlockHash should be // consistent across nodes when sending observations - resultBytes = append(resultBytes, []byte(fmt.Sprintf("%+v", r.Trigger.LogTriggerExtension))...) + resultBytes = append(resultBytes, fmt.Appendf(nil, "%+v", r.Trigger.LogTriggerExtension)...) } resultBytes = append(resultBytes, checkResultDelimiter) diff --git a/pkg/types/automation/basetypes_test.go b/pkg/types/automation/basetypes_test.go index 853addb1db..6440b53d24 100644 --- a/pkg/types/automation/basetypes_test.go +++ b/pkg/types/automation/basetypes_test.go @@ -555,16 +555,16 @@ func TestCheckResult_UniqueID(t *testing.T) { } func assertJSONEqual(t *testing.T, expected, actual string) { - var expectedMap, actualMap map[string]interface{} + var expectedMap, actualMap map[string]any require.NoError(t, json.Unmarshal([]byte(expected), &expectedMap), "expected is invalid json") require.NoError(t, json.Unmarshal([]byte(actual), &actualMap), "actual is invalid json") assert.True(t, reflect.DeepEqual(expectedMap, actualMap), "expected and result json strings do not match") } -func assertJSONContainsAllStructFields(t *testing.T, jsonString string, anyStruct interface{}) { +func assertJSONContainsAllStructFields(t *testing.T, jsonString string, anyStruct any) { // if fields are added to the struct in the future, but omitted from the "pretty" string template, this test will fail - var jsonMap map[string]interface{} - var structMap map[string]interface{} + var jsonMap map[string]any + var structMap map[string]any require.NoError(t, json.Unmarshal([]byte(jsonString), &jsonMap), "jsonString is invalid json") structJSON, err := json.Marshal(anyStruct) require.NoError(t, err) @@ -572,13 +572,13 @@ func assertJSONContainsAllStructFields(t *testing.T, jsonString string, anyStruc assertCongruentKeyStructure(t, structMap, jsonMap) } -func assertCongruentKeyStructure(t *testing.T, structMap, jsonMap map[string]interface{}) { +func assertCongruentKeyStructure(t *testing.T, structMap, jsonMap map[string]any) { // this functions asserts that the two inputs have congruent key shapes, while disregarding // the values for k := range structMap { assert.True(t, jsonMap[k] != nil, "json string does not contain field %s", k) - if nested1, ok := structMap[k].(map[string]interface{}); ok { - if nested2, ok := jsonMap[k].(map[string]interface{}); ok { + if nested1, ok := structMap[k].(map[string]any); ok { + if nested2, ok := jsonMap[k].(map[string]any); ok { assertCongruentKeyStructure(t, nested1, nested2) } else { assert.Fail(t, "maps do not contain the same type for key %s", k) diff --git a/pkg/types/ccipocr3/common_types.go b/pkg/types/ccipocr3/common_types.go index 2e333219f8..22a17045fc 100644 --- a/pkg/types/ccipocr3/common_types.go +++ b/pkg/types/ccipocr3/common_types.go @@ -75,7 +75,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 { @@ -131,7 +131,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 { @@ -178,7 +178,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/core/pipeline_runner.go b/pkg/types/core/pipeline_runner.go index 3fab4c4cce..a9e9cb9d88 100644 --- a/pkg/types/core/pipeline_runner.go +++ b/pkg/types/core/pipeline_runner.go @@ -9,7 +9,7 @@ import ( ) type Vars struct { - Vars map[string]interface{} + Vars map[string]any } type Options struct { diff --git a/pkg/types/core/validation.go b/pkg/types/core/validation.go index 03ab282f0d..21eff0adf9 100644 --- a/pkg/types/core/validation.go +++ b/pkg/types/core/validation.go @@ -8,12 +8,12 @@ import ( type ValidationService interface { services.Service - ValidateConfig(ctx context.Context, config map[string]interface{}) error + ValidateConfig(ctx context.Context, config map[string]any) error } type ValidationServiceClient interface { - ValidateConfig(ctx context.Context, config map[string]interface{}) error + ValidateConfig(ctx context.Context, config map[string]any) error } type ValidationServiceServer interface { - ValidateConfig(ctx context.Context, config map[string]interface{}) error + ValidateConfig(ctx context.Context, config map[string]any) error } diff --git a/pkg/types/evm/chain_reader.go b/pkg/types/evm/chain_reader.go index cb2a904d31..b9283e7c05 100644 --- a/pkg/types/evm/chain_reader.go +++ b/pkg/types/evm/chain_reader.go @@ -12,7 +12,7 @@ type ContractReaderConfig struct { type ChainContractReader struct { ContractABI string `json:"contractABI" toml:"contractABI"` - ContractPollingFilter ContractPollingFilter `json:"contractPollingFilter,omitempty,omitzero" toml:"contractPollingFilter,omitempty"` + ContractPollingFilter ContractPollingFilter `json:"contractPollingFilter,omitzero" toml:"contractPollingFilter,omitempty"` // key is genericName from config Configs map[string]*ChainReaderDefinition `json:"configs" toml:"configs"` } diff --git a/pkg/types/gateway/action.go b/pkg/types/gateway/action.go index c86b69ad38..00f95db5df 100644 --- a/pkg/types/gateway/action.go +++ b/pkg/types/gateway/action.go @@ -23,12 +23,12 @@ type CacheSettings struct { // OutboundHTTPRequest represents an HTTP request to be sent from workflow node to the gateway. type OutboundHTTPRequest struct { - URL string `json:"url"` // URL to query, only http and https protocols are supported. - Method string `json:"method,omitempty"` // HTTP verb, defaults to GET. - Headers map[string]string `json:"headers,omitempty"` // HTTP headers, defaults to empty. - Body []byte `json:"body,omitempty"` // HTTP request body - TimeoutMs uint32 `json:"timeoutMs,omitempty"` // Timeout in milliseconds - CacheSettings CacheSettings `json:"cacheSettings,omitempty"` // Best-effort cache control for the request + URL string `json:"url"` // URL to query, only http and https protocols are supported. + Method string `json:"method,omitempty"` // HTTP verb, defaults to GET. + Headers map[string]string `json:"headers,omitempty"` // HTTP headers, defaults to empty. + Body []byte `json:"body,omitempty"` // HTTP request body + TimeoutMs uint32 `json:"timeoutMs,omitempty"` // Timeout in milliseconds + CacheSettings CacheSettings `json:"cacheSettings"` // Best-effort cache control for the request // Maximum number of bytes to read from the response body. If the gateway max response size is smaller than this value, the gateway max response size will be used. MaxResponseBytes uint32 `json:"maxBytes,omitempty"` diff --git a/pkg/types/gateway/round_robin_selector_test.go b/pkg/types/gateway/round_robin_selector_test.go index 6a901403ab..a783c0e7aa 100644 --- a/pkg/types/gateway/round_robin_selector_test.go +++ b/pkg/types/gateway/round_robin_selector_test.go @@ -29,7 +29,7 @@ func TestNewRoundRobinSelector_NotAlwaysZero(t *testing.T) { numInstances := 100 // Check a reasonable number of instances alwaysZero := true - for i := 0; i < numInstances; i++ { + for range numInstances { selector := NewRoundRobinSelector(items) if selector.index != 0 { alwaysZero = false @@ -45,7 +45,7 @@ func TestNewRoundRobinSelector_AlwaysZero(t *testing.T) { numInstances := 100 // Check a reasonable number of instances alwaysZero := true - for i := 0; i < numInstances; i++ { + for range numInstances { selector := NewRoundRobinSelector(items, WithFixedStart()) if selector.index != 0 { alwaysZero = false @@ -71,7 +71,7 @@ func TestRoundRobinSelector_Concurrency(t *testing.T) { numRequests := 100 results := make(chan string, numRequests) - for i := 0; i < numRequests; i++ { + for range numRequests { wg.Add(1) go func() { defer wg.Done() diff --git a/pkg/types/gateway/trigger_test.go b/pkg/types/gateway/trigger_test.go index fd790afc6a..26d0e0bf7c 100644 --- a/pkg/types/gateway/trigger_test.go +++ b/pkg/types/gateway/trigger_test.go @@ -375,7 +375,7 @@ func TestHTTPTriggerRequest_MarshalJSON_Consistency(t *testing.T) { // Marshal multiple times results := make([]string, 10) - for i := 0; i < 10; i++ { + for i := range 10 { data, err := json.Marshal(request) require.NoError(t, err) results[i] = string(data) diff --git a/pkg/types/interfacetests/chain_components_interface_tests.go b/pkg/types/interfacetests/chain_components_interface_tests.go index 019c66b3c2..430be27f04 100644 --- a/pkg/types/interfacetests/chain_components_interface_tests.go +++ b/pkg/types/interfacetests/chain_components_interface_tests.go @@ -959,7 +959,7 @@ func runContractReaderBatchGetLatestValuesInterfaceTests[T TestingT[T]](t T, tes batchGetLatestValueRequest := make(types.BatchGetLatestValuesRequest) bound := BindingsByName(bindings, AnyContractName)[0] - for i := 0; i < 10; i++ { + for i := range 10 { // setup test data ts := CreateTestStruct(i, tester) batchCallEntry[bound] = append(batchCallEntry[bound], ReadEntry{Name: MethodTakingLatestParamsReturningTestStruct, ReturnValue: &ts}) @@ -977,7 +977,7 @@ func runContractReaderBatchGetLatestValuesInterfaceTests[T TestingT[T]](t T, tes result, err := cr.BatchGetLatestValues(ctx, batchGetLatestValueRequest) require.NoError(t, err) - for i := 0; i < 10; i++ { + for i := range 10 { resultAnyContract, testDataAnyContract := result[bound], batchCallEntry[bound] returnValue, err := resultAnyContract[i].GetResult() assert.NoError(t, err) @@ -997,7 +997,7 @@ func runContractReaderBatchGetLatestValuesInterfaceTests[T TestingT[T]](t T, tes bound1 := BindingsByName(bindings, AnyContractName)[0] bound2 := BindingsByName(bindings, AnySecondContractName)[0] - for i := 0; i < 10; i++ { + for i := range 10 { // setup test data ts1, ts2 := CreateTestStruct(i, tester), CreateTestStruct(i+10, tester) batchCallEntry[bound1] = append(batchCallEntry[bound1], ReadEntry{Name: MethodTakingLatestParamsReturningTestStruct, ReturnValue: &ts1}) @@ -1014,14 +1014,14 @@ func runContractReaderBatchGetLatestValuesInterfaceTests[T TestingT[T]](t T, tes result, err := cr.BatchGetLatestValues(ctx, batchGetLatestValueRequest) require.NoError(t, err) - for idx := 0; idx < 10; idx++ { + for idx := range 10 { fmt.Printf("expected: %+v\n", batchCallEntry[bound1][idx].ReturnValue) if val, err := result[bound1][idx].GetResult(); err == nil { fmt.Printf("result: %+v\n", val) } } - for i := 0; i < 10; i++ { + for i := range 10 { testDataAnyContract, testDataAnySecondContract := batchCallEntry[bound1], batchCallEntry[bound2] resultAnyContract, resultAnySecondContract := result[bound1], result[bound2] returnValueAnyContract, errAnyContract := resultAnyContract[i].GetResult() @@ -1044,7 +1044,7 @@ func runContractReaderBatchGetLatestValuesInterfaceTests[T TestingT[T]](t T, tes bound1 := BindingsByName(bindings, AnyContractName)[0] bound2 := BindingsByName(bindings, AnySecondContractName)[0] - for i := 0; i < 10; i++ { + for range 10 { // setup call data and set invalid params that cause an error batchGetLatestValueRequest[bound1] = append(batchGetLatestValueRequest[bound1], types.BatchRead{ReadName: MethodTakingLatestParamsReturningTestStruct, Params: &LatestParams{I: 0}, ReturnVal: &TestStruct{}}) batchGetLatestValueRequest[bound2] = append(batchGetLatestValueRequest[bound2], types.BatchRead{ReadName: MethodTakingLatestParamsReturningTestStruct, Params: &LatestParams{I: 0}, ReturnVal: &TestStruct{}}) @@ -1056,7 +1056,7 @@ func runContractReaderBatchGetLatestValuesInterfaceTests[T TestingT[T]](t T, tes result, err := cr.BatchGetLatestValues(ctx, batchGetLatestValueRequest) require.NoError(t, err) - for i := 0; i < 10; i++ { + for i := range 10 { resultAnyContract, resultAnySecondContract := result[bound1], result[bound2] returnValueAnyContract, errAnyContract := resultAnyContract[i].GetResult() returnValueAnySecondContract, errAnySecondContract := resultAnySecondContract[i].GetResult() diff --git a/pkg/types/llo/types.go b/pkg/types/llo/types.go index 453f2ea377..bbe442a61d 100644 --- a/pkg/types/llo/types.go +++ b/pkg/types/llo/types.go @@ -307,7 +307,7 @@ func (m ChannelOpts) MarshalJSON() ([]byte, error) { // formatJSON ensures that the JSON string is in a deterministic shape func formatJSON(input []byte) ([]byte, error) { - var obj map[string]interface{} + var obj map[string]any // Unmarshal the JSON string into a map if err := json.Unmarshal(input, &obj); err != nil { @@ -325,7 +325,7 @@ func formatJSON(input []byte) ([]byte, error) { type ChannelDefinitions map[ChannelID]ChannelDefinition -func (c *ChannelDefinitions) Scan(value interface{}) error { +func (c *ChannelDefinitions) Scan(value any) error { bytes, ok := value.([]byte) if !ok { return fmt.Errorf("failed to scan Data: value is not []byte") diff --git a/pkg/types/solana/anchoridl.go b/pkg/types/solana/anchoridl.go index 470b882d96..34aa005db4 100644 --- a/pkg/types/solana/anchoridl.go +++ b/pkg/types/solana/anchoridl.go @@ -84,7 +84,7 @@ type IdlAccountItem struct { } func (env *IdlAccountItem) UnmarshalJSON(data []byte) error { - var temp interface{} + var temp any if err := json.Unmarshal(data, &temp); err != nil { return err } @@ -94,7 +94,7 @@ func (env *IdlAccountItem) UnmarshalJSON(data []byte) error { } switch v := temp.(type) { - case map[string]interface{}: + case map[string]any: if len(v) == 0 { return nil } @@ -126,9 +126,9 @@ func (env IdlAccountItem) MarshalJSON() ([]byte, error) { return nil, err } - var result interface{} + var result any if env.IdlAccounts != nil { - result = map[string]interface{}{ + result = map[string]any{ "accounts": env.IdlAccounts, } } else { @@ -238,7 +238,7 @@ type IdlTypeArray struct { } func (env IdlType) MarshalJSON() ([]byte, error) { - var result interface{} + var result any switch { case env.IsString(): result = env.GetString() @@ -250,8 +250,8 @@ func (env IdlType) MarshalJSON() ([]byte, error) { result = env.GetIdlTypeDefined() case env.IsArray(): array := env.GetArray() - result = map[string]interface{}{ - "array": []interface{}{array.Thing, array.Num}, + result = map[string]any{ + "array": []any{array.Thing, array.Num}, } default: return nil, fmt.Errorf("nil envelope is not supported in IdlType") @@ -261,7 +261,7 @@ func (env IdlType) MarshalJSON() ([]byte, error) { } func (env *IdlType) UnmarshalJSON(data []byte) error { - var temp interface{} + var temp any if err := json.Unmarshal(data, &temp); err != nil { return err } @@ -273,7 +273,7 @@ func (env *IdlType) UnmarshalJSON(data []byte) error { switch v := temp.(type) { case string: env.AsString = IdlTypeAsString(v) - case map[string]interface{}: + case map[string]any: if len(v) == 0 { return nil } @@ -313,7 +313,7 @@ func (env *IdlType) UnmarshalJSON(data []byte) error { if typeFound { return fmt.Errorf("multiple types found for IdlType: %s", spew.Sdump(temp)) } - arrVal, ok := got.([]interface{}) + arrVal, ok := got.([]any) if !ok { return fmt.Errorf("array is not in expected format: %s", spew.Sdump(got)) } diff --git a/pkg/types/solana/contract_reader.go b/pkg/types/solana/contract_reader.go index c534f5715d..44919f19da 100644 --- a/pkg/types/solana/contract_reader.go +++ b/pkg/types/solana/contract_reader.go @@ -57,7 +57,7 @@ type ReadDefinition struct { ErrOnMissingAccountData bool `json:"errOnMissingAccountData,omitempty"` InputModifications codec.ModifiersConfig `json:"inputModifications,omitempty"` OutputModifications codec.ModifiersConfig `json:"outputModifications,omitempty"` - PDADefinition PDATypeDef `json:"pdaDefinition,omitempty"` // Only used for PDA account reads + PDADefinition PDATypeDef `json:"pdaDefinition"` // Only used for PDA account reads MultiReader *MultiReader `json:"multiReader,omitempty"` EventDefinitions *EventDefinitions `json:"eventDefinitions,omitempty"` // ResponseAddressHardCoder hardcodes the address of the contract into the defined field in the response. diff --git a/pkg/types/solana/contract_writer.go b/pkg/types/solana/contract_writer.go index 221a96d7be..b9688bf7f3 100644 --- a/pkg/types/solana/contract_writer.go +++ b/pkg/types/solana/contract_writer.go @@ -16,7 +16,7 @@ type MethodConfig struct { FromAddress string `json:"fromAddress"` InputModifications codec.ModifiersConfig `json:"inputModifications,omitempty"` ChainSpecificName string `json:"chainSpecificName"` - LookupTables LookupTables `json:"lookupTables,omitempty"` + LookupTables LookupTables `json:"lookupTables"` Accounts []Lookup `json:"accounts"` ATAs []ATALookup `json:"atas,omitempty"` // Location in the args where the debug ID is stored diff --git a/pkg/types/solana/lookups.go b/pkg/types/solana/lookups.go index 0a78f33f4d..1565efb3bf 100644 --- a/pkg/types/solana/lookups.go +++ b/pkg/types/solana/lookups.go @@ -25,8 +25,8 @@ type AccountLookup struct { Name string `json:"name,omitempty"` Location string `json:"location"` // IsSigner and IsWritable can either be a constant bool or a location to a bitmap which decides the bools - IsSigner MetaBool `json:"isSigner,omitempty"` - IsWritable MetaBool `json:"isWritable,omitempty"` + IsSigner MetaBool `json:"isSigner"` + IsWritable MetaBool `json:"isWritable"` } type MetaBool struct { @@ -35,8 +35,8 @@ type MetaBool struct { } type Seed struct { - Static []byte `json:"static,omitempty"` // Static seed value - Dynamic Lookup `json:"dynamic,omitempty"` // Dynamic lookup for seed + Static []byte `json:"static,omitempty"` // Static seed value + Dynamic Lookup `json:"dynamic"` // Dynamic lookup for seed } // PDALookups generates Program Derived Addresses (PDA) by combining a derived public key with one or more seeds. @@ -50,7 +50,7 @@ type PDALookups struct { IsSigner bool `json:"isSigner,omitempty"` IsWritable bool `json:"isWritable,omitempty"` // OPTIONAL: On-chain location and type of desired data from PDA (e.g. a sub-account of the data account) - InternalField InternalField `json:"internalField,omitempty"` + InternalField InternalField `json:"internalField"` } type InternalField struct { diff --git a/pkg/utils/collection_test.go b/pkg/utils/collection_test.go index f956192d3a..02b6b276a5 100644 --- a/pkg/utils/collection_test.go +++ b/pkg/utils/collection_test.go @@ -8,7 +8,7 @@ import ( func TestBatchSplit(t *testing.T) { list := []int{} - for i := 0; i < 100; i++ { + for i := range 100 { list = append(list, i) } @@ -42,7 +42,7 @@ func TestBatchSplit(t *testing.T) { assert.Equal(t, r.num, len(batch)) // check number of batches temp := []int{} - for i := 0; i < len(batch); i++ { + for i := range batch { expectedLen := r.max if i == len(batch)-1 { expectedLen = r.lastLen // expect last batch to be less than max diff --git a/pkg/utils/jsonserializable/json_serializable.go b/pkg/utils/jsonserializable/json_serializable.go index 91e3846375..049cd99739 100644 --- a/pkg/utils/jsonserializable/json_serializable.go +++ b/pkg/utils/jsonserializable/json_serializable.go @@ -12,16 +12,16 @@ import ( ) type JSONSerializable struct { - Val interface{} + Val any Valid bool } -func ReinterpretJSONNumbers(val interface{}) (interface{}, error) { +func ReinterpretJSONNumbers(val any) (any, error) { switch v := val.(type) { case json.Number: return getJSONNumberValue(v) - case []interface{}: - s := make([]interface{}, len(v)) + case []any: + s := make([]any, len(v)) for i, vv := range v { ival, ierr := ReinterpretJSONNumbers(vv) if ierr != nil { @@ -30,8 +30,8 @@ func ReinterpretJSONNumbers(val interface{}) (interface{}, error) { s[i] = ival } return s, nil - case map[string]interface{}: - m := make(map[string]interface{}, len(v)) + case map[string]any: + m := make(map[string]any, len(v)) for k, vv := range v { ival, ierr := ReinterpretJSONNumbers(vv) if ierr != nil { @@ -54,7 +54,7 @@ func (js *JSONSerializable) UnmarshalJSON(bs []byte) error { return nil } - var decoded interface{} + var decoded any d := json.NewDecoder(bytes.NewReader(bs)) d.UseNumber() if err := d.Decode(&decoded); err != nil { @@ -85,7 +85,7 @@ func (js JSONSerializable) MarshalJSON() ([]byte, error) { return json.Marshal(jsWithHex) } -func (js *JSONSerializable) Scan(value interface{}) error { +func (js *JSONSerializable) Scan(value any) error { if value == nil { *js = JSONSerializable{} return nil @@ -112,7 +112,7 @@ func (js *JSONSerializable) Empty() bool { } // replaceBytesWithHex replaces all []byte with hex-encoded strings -func replaceBytesWithHex(val interface{}) interface{} { +func replaceBytesWithHex(val any) any { if v, ok := val.(interface{ Hex() string }); ok { return v.Hex() } @@ -128,20 +128,20 @@ func replaceBytesWithHex(val interface{}) interface{} { list = append(list, stringToHex(string(bytes))) } return list - case []interface{}: + case []any: if value == nil { return value } - var list []interface{} + var list []any for _, item := range value { list = append(list, replaceBytesWithHex(item)) } return list - case map[string]interface{}: + case map[string]any: if value == nil { return value } - m := make(map[string]interface{}) + m := make(map[string]any) for k, v := range value { m[k] = replaceBytesWithHex(v) } @@ -172,7 +172,7 @@ func replaceBytesWithHex(val interface{}) interface{} { } // uint8ArrayToSlice converts [N]uint8 array to slice. -func uint8ArrayToSlice(arr interface{}) interface{} { +func uint8ArrayToSlice(arr any) any { t := reflect.TypeOf(arr) if t.Kind() != reflect.Array || t.Elem().Kind() != reflect.Uint8 { return nil @@ -183,8 +183,8 @@ func uint8ArrayToSlice(arr interface{}) interface{} { return s.Interface() } -func getJSONNumberValue(value json.Number) (interface{}, error) { - var result interface{} +func getJSONNumberValue(value json.Number) (any, error) { + var result any bn, ok := new(big.Int).SetString(value.String(), 10) if ok { diff --git a/pkg/utils/jsonserializable/json_serializable_test.go b/pkg/utils/jsonserializable/json_serializable_test.go index acf8b65ba6..d0b780927a 100644 --- a/pkg/utils/jsonserializable/json_serializable_test.go +++ b/pkg/utils/jsonserializable/json_serializable_test.go @@ -22,7 +22,7 @@ func (h hexable) Hex() string { func TestMarshalJSONSerializable_replaceBytesWithHex(t *testing.T) { t.Parallel() - type jsm = map[string]interface{} + type jsm = map[string]any toJSONSerializable := func(val jsm) *jsonserializable.JSONSerializable { return &jsonserializable.JSONSerializable{ @@ -58,7 +58,7 @@ func TestMarshalJSONSerializable_replaceBytesWithHex(t *testing.T) { `{"addresses":["0x2ab9a2dc53736B361b72d900CdF9F78F9406f111","0x2ab9a2dc53736B361b72d900CdF9F78F9406f222"]}`, nil}, {"slice of hashes", toJSONSerializable(jsm{"hashes": []hexable{testHash1, testHash2}}), `{"hashes":["0x317cfd032b5d6657995f17fe768f7cc4ea0ada27ad421c4caa685a9071eaf111","0x317cfd032b5d6657995f17fe768f7cc4ea0ada27ad421c4caa685a9071eaf222"]}`, nil}, - {"slice of interfaces", toJSONSerializable(jsm{"ifaces": []interface{}{[]byte{0x10, 0x11, 0x12}, []byte{0x20, 0x21, 0x22}}}), + {"slice of interfaces", toJSONSerializable(jsm{"ifaces": []any{[]byte{0x10, 0x11, 0x12}, []byte{0x20, 0x21, 0x22}}}), `{"ifaces":["0x101112","0x202122"]}`, nil}, {"map", toJSONSerializable(jsm{"map": jsm{"slice": []byte{0x10, 0x11, 0x12}, "addr": testAddr1}}), `{"map":{"addr":"0x2ab9a2dc53736B361b72d900CdF9F78F9406f111","slice":"0x101112"}}`, nil}, @@ -85,16 +85,16 @@ func TestUnmarshalJSONSerializable(t *testing.T) { tests := []struct { name, input string - expected interface{} + expected any }{ {"null json", `null`, nil}, {"bool", `true`, true}, {"string", `"foo"`, "foo"}, - {"object with int", `{"foo": 42}`, map[string]interface{}{"foo": int64(42)}}, - {"object with float", `{"foo": 3.14}`, map[string]interface{}{"foo": float64(3.14)}}, - {"object with big int", `{"foo": 18446744073709551616}`, map[string]interface{}{"foo": big}}, - {"slice", `[42, 3.14]`, []interface{}{int64(42), float64(3.14)}}, - {"nested map", `{"m": {"foo": 42}}`, map[string]interface{}{"m": map[string]interface{}{"foo": int64(42)}}}, + {"object with int", `{"foo": 42}`, map[string]any{"foo": int64(42)}}, + {"object with float", `{"foo": 3.14}`, map[string]any{"foo": float64(3.14)}}, + {"object with big int", `{"foo": 18446744073709551616}`, map[string]any{"foo": big}}, + {"slice", `[42, 3.14]`, []any{int64(42), float64(3.14)}}, + {"nested map", `{"m": {"foo": 42}}`, map[string]any{"m": map[string]any{"foo": int64(42)}}}, } for _, test := range tests { diff --git a/pkg/utils/mailbox/mailbox_test.go b/pkg/utils/mailbox/mailbox_test.go index 8c63d96ddf..d9f13c381f 100644 --- a/pkg/utils/mailbox/mailbox_test.go +++ b/pkg/utils/mailbox/mailbox_test.go @@ -113,7 +113,7 @@ func TestMailbox_NoEmptyReceivesWhenCapacityIsTwo(t *testing.T) { } }() - for i := 0; i < 100000; i++ { + for i := range 100000 { m.Deliver(i) } close(m.chNotify) diff --git a/pkg/utils/null/uint32.go b/pkg/utils/null/uint32.go index fa0123fb60..88c28cd894 100644 --- a/pkg/utils/null/uint32.go +++ b/pkg/utils/null/uint32.go @@ -33,7 +33,7 @@ func Uint32From(i uint32) Uint32 { // 0 will not be considered a null Int. func (i *Uint32) UnmarshalJSON(data []byte) error { var err error - var v interface{} + var v any if err = json.Unmarshal(data, &v); err != nil { return err } @@ -114,7 +114,7 @@ func (i Uint32) Value() (driver.Value, error) { } // Scan reads the database value and returns an instance. -func (i *Uint32) Scan(value interface{}) error { +func (i *Uint32) Scan(value any) error { if value == nil { *i = Uint32{} return nil diff --git a/pkg/utils/sleeper_task_test.go b/pkg/utils/sleeper_task_test.go index 27d7dd9e22..bc632cd362 100644 --- a/pkg/utils/sleeper_task_test.go +++ b/pkg/utils/sleeper_task_test.go @@ -104,7 +104,7 @@ func TestSleeperTask_WakeupEnqueuesMaxTwice(t *testing.T) { worker.ignoreSignals = true worker.allowResumeWork <- struct{}{} - for i := 0; i < 2; i++ { + for range 2 { select { case <-worker.ch: case <-ctx.Done(): diff --git a/pkg/utils/testutils.go b/pkg/utils/testutils.go index 6b45e12ce8..19ef024edf 100644 --- a/pkg/utils/testutils.go +++ b/pkg/utils/testutils.go @@ -22,7 +22,7 @@ func Context(t *testing.T) context.Context { func AssertJSONEqual(t tests.TestingT, x []byte, y []byte) { var TransformJSON = cmp.FilterValues(func(x, y []byte) bool { return json.Valid(x) && json.Valid(y) - }, cmp.Transformer("ParseJSON", func(in []byte) (out interface{}) { + }, cmp.Transformer("ParseJSON", func(in []byte) (out any) { if err := json.Unmarshal(in, &out); err != nil { panic(err) // should never occur given previous filter to ensure valid JSON } diff --git a/pkg/utils/utils.go b/pkg/utils/utils.go index 6a60d26297..0099f351ec 100644 --- a/pkg/utils/utils.go +++ b/pkg/utils/utils.go @@ -42,7 +42,7 @@ func IsZero[C comparable](val C) bool { } // JustError takes a tuple and returns the last entry, the error. -func JustError(_ interface{}, err error) error { +func JustError(_ any, err error) error { return err } diff --git a/pkg/workflows/dontime/store.go b/pkg/workflows/dontime/store.go index b434a85b96..b0354c73f5 100644 --- a/pkg/workflows/dontime/store.go +++ b/pkg/workflows/dontime/store.go @@ -2,6 +2,7 @@ package dontime import ( "fmt" + "maps" "sync" "time" ) @@ -39,9 +40,7 @@ func (s *Store) GetRequests() map[string]*Request { s.mu.Lock() defer s.mu.Unlock() copied := make(map[string]*Request) - for k, v := range s.requests { - copied[k] = v - } + maps.Copy(copied, s.requests) return copied } diff --git a/pkg/workflows/models_yaml_test.go b/pkg/workflows/models_yaml_test.go index 89ca32fff1..2f83c69099 100644 --- a/pkg/workflows/models_yaml_test.go +++ b/pkg/workflows/models_yaml_test.go @@ -41,7 +41,7 @@ func yamlFixtureReaderBytes(t *testing.T, testCase string) func(name string) []b var transformJSON = cmp.FilterValues(func(x, y []byte) bool { return json.Valid(x) && json.Valid(y) -}, cmp.Transformer("ParseJSON", func(in []byte) (out interface{}) { +}, cmp.Transformer("ParseJSON", func(in []byte) (out any) { if err := json.Unmarshal(in, &out); err != nil { panic(err) // should never occur given previous filter to ensure valid JSON } @@ -60,7 +60,7 @@ func TestWorkflowSpecMarshalling(t *testing.T) { require.NoError(t, err) // Test that our workflowSpec still keeps all of the original data - var rawSpec interface{} + var rawSpec any err = yaml.Unmarshal(workflowBytes, &rawSpec) require.NoError(t, err) @@ -91,7 +91,7 @@ func TestWorkflowSpecMarshalling(t *testing.T) { // check bools bools, ok := booleanCoercions["bools"] require.True(t, ok, "expected bools to be present in boolean_coercions") - for _, v := range bools.([]interface{}) { + for _, v := range bools.([]any) { _, ok = v.(bool) require.True(t, ok, "expected bool but got %T", v) } @@ -99,7 +99,7 @@ func TestWorkflowSpecMarshalling(t *testing.T) { // check strings strings, ok := booleanCoercions["strings"] require.True(t, ok, "expected strings to be present in boolean_coercions") - for _, v := range strings.([]interface{}) { + for _, v := range strings.([]any) { _, ok = v.(string) require.True(t, ok, "expected string but got %T", v) } @@ -107,7 +107,7 @@ func TestWorkflowSpecMarshalling(t *testing.T) { // check numbers numbers, ok := booleanCoercions["numbers"] require.True(t, ok, "expected numbers to be present in boolean_coercions") - for _, v := range numbers.([]interface{}) { + for _, v := range numbers.([]any) { _, ok = v.(int64) require.True(t, ok, "expected int64 but got %T", v) } @@ -121,7 +121,7 @@ func TestWorkflowSpecMarshalling(t *testing.T) { require.NoError(t, err) // Test that our workflowSpec still keeps all of the original data - var rawSpec interface{} + var rawSpec any err = yaml.Unmarshal(workflowBytes, &rawSpec) require.NoError(t, err) diff --git a/pkg/workflows/secrets/secrets.go b/pkg/workflows/secrets/secrets.go index 830512eba2..a5ab4c73f4 100644 --- a/pkg/workflows/secrets/secrets.go +++ b/pkg/workflows/secrets/secrets.go @@ -6,6 +6,7 @@ import ( "encoding/hex" "encoding/json" "fmt" + "slices" "strings" "golang.org/x/crypto/nacl/box" @@ -45,12 +46,7 @@ type EncryptedSecretsResult struct { } func ContainsP2pId(p2pId [32]byte, p2pIds [][32]byte) bool { - for _, id := range p2pIds { - if id == p2pId { - return true - } - } - return false + return slices.Contains(p2pIds, p2pId) } func EncryptSecretsForNodes( diff --git a/pkg/workflows/secrets/secrets_test.go b/pkg/workflows/secrets/secrets_test.go index 4bc441958c..aec105c6ee 100644 --- a/pkg/workflows/secrets/secrets_test.go +++ b/pkg/workflows/secrets/secrets_test.go @@ -229,11 +229,11 @@ func TestValidateEncryptedSecrets(t *testing.T) { keyFromMetadata := [32]byte{1, 2, 3} // Valid JSON input with matching workflow owner - validInput := map[string]interface{}{ + validInput := map[string]any{ "encryptedSecrets": map[string]string{ "09ca39cd924653c72fbb0e458b629c3efebdad3e29e7cd0b5760754d919ed829": validBase64("secret1"), }, - "metadata": map[string]interface{}{ + "metadata": map[string]any{ "workflowOwner": "correctOwner", "nodePublicEncryptionKeys": map[string]string{ "09ca39cd924653c72fbb0e458b629c3efebdad3e29e7cd0b5760754d919ed829": hex.EncodeToString(keyFromMetadata[:]), diff --git a/pkg/workflows/wasm/host/execution.go b/pkg/workflows/wasm/host/execution.go index 1307ffaa82..8848e07508 100644 --- a/pkg/workflows/wasm/host/execution.go +++ b/pkg/workflows/wasm/host/execution.go @@ -263,7 +263,7 @@ func (e *execution[T]) pollOneoff(caller *wasmtime.Caller, subscriptionptr int32 events := make([]byte, nsubscriptions*eventsLen) timeout := time.Duration(0) - for i := int32(0); i < nsubscriptions; i++ { + for i := range nsubscriptions { inOffset := i * subscriptionLen userData := subs[inOffset : inOffset+8] eventType := subs[inOffset+8] diff --git a/pkg/workflows/wasm/host/module.go b/pkg/workflows/wasm/host/module.go index 00639ba941..ade6d044d4 100644 --- a/pkg/workflows/wasm/host/module.go +++ b/pkg/workflows/wasm/host/module.go @@ -858,7 +858,7 @@ func createLogFn(logger logger.Logger) func(caller *wasmtime.Caller, ptr int32, return } - var raw map[string]interface{} + var raw map[string]any innerErr = json.Unmarshal(b, &raw) if innerErr != nil { return @@ -871,7 +871,7 @@ func createLogFn(logger logger.Logger) func(caller *wasmtime.Caller, ptr int32, delete(raw, "msg") delete(raw, "ts") - var args []interface{} + var args []any for k, v := range raw { args = append(args, k, v) } diff --git a/pkg/workflows/wasm/host/standard_test.go b/pkg/workflows/wasm/host/standard_test.go index 2538642739..1ae7ac135b 100644 --- a/pkg/workflows/wasm/host/standard_test.go +++ b/pkg/workflows/wasm/host/standard_test.go @@ -590,7 +590,7 @@ func assertProto[T proto.Message](t *testing.T, expected, actual T) { diff := cmp.Diff(expected, actual, protocmp.Transform()) var sb strings.Builder - for _, line := range strings.Split(diff, "\n") { + for line := range strings.SplitSeq(diff, "\n") { if strings.HasPrefix(line, "+") || strings.HasPrefix(line, "-") { sb.WriteString(line + "\n") } diff --git a/pkg/workflows/wasm/host/time_test.go b/pkg/workflows/wasm/host/time_test.go index b35eb2698d..b792588c99 100644 --- a/pkg/workflows/wasm/host/time_test.go +++ b/pkg/workflows/wasm/host/time_test.go @@ -12,8 +12,7 @@ import ( ) func TestTimeFetcher_GetTime_NODE(t *testing.T) { - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() + ctx := t.Context() mockExec := NewMockExecutionHelper(t) expected := time.Now() @@ -28,8 +27,7 @@ func TestTimeFetcher_GetTime_NODE(t *testing.T) { } func TestTimeFetcher_GetTime_DON(t *testing.T) { - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() + ctx := t.Context() mockExec := NewMockExecutionHelper(t) expected := time.Now() @@ -44,8 +42,7 @@ func TestTimeFetcher_GetTime_DON(t *testing.T) { } func TestTimeFetcher_GetTime_DON_Error(t *testing.T) { - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() + ctx := t.Context() mockExec := NewMockExecutionHelper(t) mockExec.EXPECT().GetDONTime().Return(time.Time{}, errors.New("don error")) diff --git a/pkg/workflows/wasm/host/wasip1.go b/pkg/workflows/wasm/host/wasip1.go index 5a1a31ef27..b1d58b286d 100644 --- a/pkg/workflows/wasm/host/wasip1.go +++ b/pkg/workflows/wasm/host/wasip1.go @@ -148,7 +148,7 @@ func pollOneoff(caller *wasmtime.Caller, subscriptionptr int32, eventsptr int32, events := make([]byte, nsubscriptions*eventsLen) timeout := time.Duration(0) - for i := int32(0); i < nsubscriptions; i++ { + for i := range nsubscriptions { // First, let's read the subscription inOffset := i * subscriptionLen diff --git a/pkg/workflows/wasm/host/wasip1_test.go b/pkg/workflows/wasm/host/wasip1_test.go index bfe9292d0b..6ae6f951ff 100644 --- a/pkg/workflows/wasm/host/wasip1_test.go +++ b/pkg/workflows/wasm/host/wasip1_test.go @@ -18,7 +18,7 @@ func TestGetSlot(t *testing.T) { {250, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63}, } - for i := int32(0); i < 2; i++ { + for i := range int32(2) { slot, err := getSlot(events, i) assert.NoError(t, err) assert.Equal(t, expectedSlots[i], slot) diff --git a/pkg/workflows/wasm/runner_test.go b/pkg/workflows/wasm/runner_test.go index 40d8439434..59ecda1a70 100644 --- a/pkg/workflows/wasm/runner_test.go +++ b/pkg/workflows/wasm/runner_test.go @@ -203,7 +203,7 @@ func TestRunner_Run_ExecuteCompute(t *testing.T) { }, { name: "valid compute func - list", - expectedOutput: []interface{}([]interface{}{int64(1), int64(2), int64(3), int64(4)}), + expectedOutput: []any([]any{int64(1), int64(2), int64(3), int64(4)}), compute: func(workflow *sdk.WorkflowSpecFactory, trigger basictrigger.TriggerOutputsCap) { sdk.Compute1( workflow, @@ -218,7 +218,7 @@ func TestRunner_Run_ExecuteCompute(t *testing.T) { }, { name: "valid compute func - map", - expectedOutput: map[string]interface{}(map[string]interface{}{"test": int64(1)}), + expectedOutput: map[string]any(map[string]any{"test": int64(1)}), compute: func(workflow *sdk.WorkflowSpecFactory, trigger basictrigger.TriggerOutputsCap) { sdk.Compute1( workflow, @@ -234,7 +234,7 @@ func TestRunner_Run_ExecuteCompute(t *testing.T) { }, { name: "valid compute func - deep map", - expectedOutput: map[string]interface{}(map[string]interface{}{"test1": map[string]interface{}{"test2": int64(1)}}), + expectedOutput: map[string]any(map[string]any{"test1": map[string]any{"test2": int64(1)}}), compute: func(workflow *sdk.WorkflowSpecFactory, trigger basictrigger.TriggerOutputsCap) { sdk.Compute1( workflow, @@ -265,7 +265,7 @@ func TestRunner_Run_ExecuteCompute(t *testing.T) { }, { name: "valid compute func - struct", - expectedOutput: map[string]interface{}(map[string]interface{}{"SomeInt": int64(3), "SomeString": "hiya", "SomeTime": now}), + expectedOutput: map[string]any(map[string]any{"SomeInt": int64(3), "SomeString": "hiya", "SomeTime": now}), compute: func(workflow *sdk.WorkflowSpecFactory, trigger basictrigger.TriggerOutputsCap) { sdk.Compute1( workflow, @@ -286,8 +286,8 @@ func TestRunner_Run_ExecuteCompute(t *testing.T) { workflow, "compute", sdk.Compute1Inputs[basictrigger.TriggerOutputs]{Arg0: trigger}, - func(sdk sdk.Runtime, outputs basictrigger.TriggerOutputs) (interface{}, error) { - var empty interface{} + func(sdk sdk.Runtime, outputs basictrigger.TriggerOutputs) (any, error) { + var empty any return empty, nil }, ) @@ -341,7 +341,7 @@ func TestRunner_Run_ExecuteCompute(t *testing.T) { }, { name: "valid compute func - private struct", - expectedOutput: map[string]interface{}(map[string]interface{}{"SomeInt": int64(3), "SomeString": "hiya"}), + expectedOutput: map[string]any(map[string]any{"SomeInt": int64(3), "SomeString": "hiya"}), compute: func(workflow *sdk.WorkflowSpecFactory, trigger basictrigger.TriggerOutputsCap) { sdk.Compute1( workflow,