diff --git a/observability-lib/grafana/businessvariable/panel_builder.go b/observability-lib/grafana/businessvariable/panel_builder.go index 3704105f15..7a1f585b5a 100644 --- a/observability-lib/grafana/businessvariable/panel_builder.go +++ b/observability-lib/grafana/businessvariable/panel_builder.go @@ -92,7 +92,7 @@ func (builder *PanelBuilder) GridPos(gridPos dashboard.GridPos) *PanelBuilder { // Panel height. The height is the number of rows from the top edge of the panel. func (builder *PanelBuilder) Height(h uint32) *PanelBuilder { - if !(h > 0) { + if h <= 0 { builder.errors["h"] = cog.MakeBuildErrors("h", errors.New("h must be > 0")) return builder } @@ -106,11 +106,11 @@ func (builder *PanelBuilder) Height(h uint32) *PanelBuilder { // Panel width. The width is the number of columns from the left edge of the panel. func (builder *PanelBuilder) Span(w uint32) *PanelBuilder { - if !(w > 0) { + if w <= 0 { builder.errors["w"] = cog.MakeBuildErrors("w", errors.New("w must be > 0")) return builder } - if !(w <= 24) { + if w > 24 { builder.errors["w"] = cog.MakeBuildErrors("w", errors.New("w must be <= 24")) return builder } diff --git a/observability-lib/grafana/polystat/panel_builder.go b/observability-lib/grafana/polystat/panel_builder.go index becb529209..3bc518dba5 100644 --- a/observability-lib/grafana/polystat/panel_builder.go +++ b/observability-lib/grafana/polystat/panel_builder.go @@ -93,7 +93,7 @@ func (builder *PanelBuilder) GridPos(gridPos dashboard.GridPos) *PanelBuilder { // Panel height. The height is the number of rows from the top edge of the panel. func (builder *PanelBuilder) Height(h uint32) *PanelBuilder { - if !(h > 0) { + if h <= 0 { builder.errors["h"] = cog.MakeBuildErrors("h", errors.New("h must be > 0")) return builder } @@ -107,11 +107,11 @@ func (builder *PanelBuilder) Height(h uint32) *PanelBuilder { // Panel width. The width is the number of columns from the left edge of the panel. func (builder *PanelBuilder) Span(w uint32) *PanelBuilder { - if !(w > 0) { + if w <= 0 { builder.errors["w"] = cog.MakeBuildErrors("w", errors.New("w must be > 0")) return builder } - if !(w <= 24) { + if w > 24 { builder.errors["w"] = cog.MakeBuildErrors("w", errors.New("w must be <= 24")) return builder } diff --git a/pkg/beholder/client_test.go b/pkg/beholder/client_test.go index e64780db39..f3f9d8dbc2 100644 --- a/pkg/beholder/client_test.go +++ b/pkg/beholder/client_test.go @@ -495,9 +495,6 @@ func TestNewClient_Chip(t *testing.T) { assert.NotNil(t, client) assert.NotNil(t, client.Chip) - // Verify it implements the Client interface - var _ chipingress.Client = client.Chip - // Verify the emitter is configured as dual source assert.NotNil(t, client.Emitter) assert.IsType(t, &beholder.DualSourceEmitter{}, client.Emitter) @@ -514,9 +511,6 @@ func TestNewClient_Chip(t *testing.T) { assert.NotNil(t, client) assert.NotNil(t, client.Chip) - // Verify it implements the Client interface - var _ chipingress.Client = client.Chip - // Verify emitter is not dual source when dual emitter is disabled assert.NotNil(t, client.Emitter) }) diff --git a/pkg/beholder/global_test.go b/pkg/beholder/global_test.go index df57d0a41b..8de51370ba 100644 --- a/pkg/beholder/global_test.go +++ b/pkg/beholder/global_test.go @@ -33,13 +33,12 @@ func TestGlobal(t *testing.T) { expectedMessageEmitter := beholder.NewNoopClient().Emitter assert.IsType(t, expectedMessageEmitter, messageEmitter) - var noopClientPtr *beholder.Client = noopClient - assert.IsType(t, noopClientPtr, beholder.GetClient()) - assert.NotSame(t, noopClientPtr, beholder.GetClient()) + assert.IsType(t, noopClient, beholder.GetClient()) + assert.NotSame(t, noopClient, beholder.GetClient()) // Set beholder client so it will be accessible from anywhere through beholder functions - beholder.SetClient(noopClientPtr) - assert.Same(t, noopClientPtr, beholder.GetClient()) + beholder.SetClient(noopClient) + assert.Same(t, noopClient, beholder.GetClient()) // After that use beholder functions to get logger, tracer, meter, messageEmitter logger, tracer, meter, messageEmitter = beholder.GetLogger(), beholder.GetTracer(), beholder.GetMeter(), beholder.GetEmitter() diff --git a/pkg/beholder/noop_test.go b/pkg/beholder/noop_test.go index 17c9cb04ef..332c677f1d 100644 --- a/pkg/beholder/noop_test.go +++ b/pkg/beholder/noop_test.go @@ -55,7 +55,6 @@ func TestNoopClient(t *testing.T) { // Chip - verify noop chip client is initialized and functional assert.NotNil(t, noopClient.Chip) - var _ chipingress.Client = noopClient.Chip assert.IsType(t, &chipingress.NoopClient{}, noopClient.Chip) // Test Chip methods return no errors diff --git a/pkg/billing/workflow_client.go b/pkg/billing/workflow_client.go index c307cd10b9..bf3294c120 100644 --- a/pkg/billing/workflow_client.go +++ b/pkg/billing/workflow_client.go @@ -43,7 +43,6 @@ type workflowClient struct { } type workflowConfig struct { - log logger.Logger transportCredentials credentials.TransportCredentials tlsCert string serverName string diff --git a/pkg/capabilities/cli/cmd/generate_types.go b/pkg/capabilities/cli/cmd/generate_types.go index 9a1648c98d..6e52aea651 100644 --- a/pkg/capabilities/cli/cmd/generate_types.go +++ b/pkg/capabilities/cli/cmd/generate_types.go @@ -179,7 +179,7 @@ func ConfigFromSchemas(schemaFilePaths []string) (ConfigInfo, error) { SchemaOutputFile: outputName, } - configInfo.Config.SchemaMappings = append(configInfo.Config.SchemaMappings, generator.SchemaMapping{ + configInfo.SchemaMappings = append(configInfo.SchemaMappings, generator.SchemaMapping{ SchemaID: jsonSchema.ID, PackageName: path.Dir(jsonSchema.ID[8:]), RootType: rootType, diff --git a/pkg/capabilities/cli/cmd/go_reader.go b/pkg/capabilities/cli/cmd/go_reader.go index aad2e9ad63..3e8a41fc2e 100644 --- a/pkg/capabilities/cli/cmd/go_reader.go +++ b/pkg/capabilities/cli/cmd/go_reader.go @@ -136,9 +136,7 @@ func (g *GoStructReader) gatherImports(node *ast.File, structs map[string]Struct } } - var allValues []string var imports []string - var check []bool for _, imp := range node.Imports { var importName string if imp.Name != nil { @@ -149,8 +147,6 @@ func (g *GoStructReader) gatherImports(node *ast.File, structs map[string]Struct } importName = strings.Trim(importName, "\"") - allValues = append(allValues, importName) - check = append(check, requiredImports[importName]) if requiredImports[importName] { imports = append(imports, imp.Path.Value) } diff --git a/pkg/capabilities/consensus/ocr3/batching_test.go b/pkg/capabilities/consensus/ocr3/batching_test.go index a2d1282991..3d8d83f695 100644 --- a/pkg/capabilities/consensus/ocr3/batching_test.go +++ b/pkg/capabilities/consensus/ocr3/batching_test.go @@ -180,7 +180,8 @@ func TestQueryBatchHasCapacity(t *testing.T) { t.Run(tt.name, func(t *testing.T) { // Handle special edge case tests that need dynamic size calculation sizeLimit := tt.sizeLimit - if tt.name == "exactly at limit boundary" { + switch tt.name { + case "exactly at limit boundary": // Calculate exact size needed for the new ID newIdSize := calculateIdSize(tt.newId) if newIdSize > 0 { @@ -190,7 +191,7 @@ func TestQueryBatchHasCapacity(t *testing.T) { } else { sizeLimit = 0 } - } else if tt.name == "one byte over limit" { + case "one byte over limit": // Calculate exact size needed for the new ID minus 1 newIdSize := calculateIdSize(tt.newId) if newIdSize > 0 { @@ -1334,14 +1335,15 @@ func TestReportBatchHasCapacity(t *testing.T) { t.Run(tt.name, func(t *testing.T) { // Handle special edge case tests that need dynamic size calculation sizeLimit := tt.sizeLimit - if tt.name == "exactly at limit boundary" { + switch tt.name { + case "exactly at limit boundary": // Calculate exact size needed for the new report newReportSize := calculateReportSize(tt.newReport) // Always include tag and length overhead, even for empty messages tagSize := varintSize(uint64(2<<3 | 2)) lengthSize := varintSize(uint64(newReportSize)) sizeLimit = tagSize + lengthSize + newReportSize - } else if tt.name == "one byte over limit" { + case "one byte over limit": // Calculate exact size needed for the new report minus 1 newReportSize := calculateReportSize(tt.newReport) // Always include tag and length overhead, even for empty messages diff --git a/pkg/chainreader/contract_reader_test.go b/pkg/chainreader/contract_reader_test.go index 4678632b8b..6b8b9c716e 100644 --- a/pkg/chainreader/contract_reader_test.go +++ b/pkg/chainreader/contract_reader_test.go @@ -141,9 +141,10 @@ func TestContractReaderByIDsQueryKey(t *testing.T) { // Mock QueryKey function mockReader.queryKeyFunc = func(ctx context.Context, contract types.BoundContract, filter query.KeyFilter, limitAndSort query.LimitAndSort, sequenceDataType any) ([]types.Sequence, error) { - if contract == bc1 { + switch contract { + case bc1: return []types.Sequence{{Data: "sequenceData1"}}, nil - } else if contract == bc2 { + case bc2: return []types.Sequence{{Data: "sequenceData2"}}, nil } return nil, fmt.Errorf("not found") diff --git a/pkg/chains/aptos/proto_helpers.go b/pkg/chains/aptos/proto_helpers.go index ce1573a0fc..57c0c92bd4 100644 --- a/pkg/chains/aptos/proto_helpers.go +++ b/pkg/chains/aptos/proto_helpers.go @@ -34,9 +34,7 @@ func ConvertViewPayloadFromProto(proto *ViewPayload) (*typeaptos.ViewPayload, er } args := make([][]byte, len(proto.Args)) - for i, protoArg := range proto.Args { - args[i] = protoArg - } + copy(args, proto.Args) return &typeaptos.ViewPayload{ Module: module, @@ -67,9 +65,7 @@ func ConvertViewPayloadToProto(payload *typeaptos.ViewPayload) (*ViewPayload, er } protoArgs := make([][]byte, len(payload.Args)) - for i, arg := range payload.Args { - protoArgs[i] = arg - } + copy(protoArgs, payload.Args) return &ViewPayload{ Module: protoModule, diff --git a/pkg/chains/nodes.go b/pkg/chains/nodes.go index b56e0c0eb6..4a3fb4ba51 100644 --- a/pkg/chains/nodes.go +++ b/pkg/chains/nodes.go @@ -53,7 +53,7 @@ func NewPageToken(b64enc string) (*pageToken, error) { if err != nil { return nil, err } - if !(vals.Has("page") && vals.Has("size")) { + if !vals.Has("page") || !vals.Has("size") { return nil, ErrInvalidToken } page, err := strconv.Atoi(vals.Get("page")) diff --git a/pkg/chains/solana/proto_helpers.go b/pkg/chains/solana/proto_helpers.go index b3acdf5ed4..228e3281de 100644 --- a/pkg/chains/solana/proto_helpers.go +++ b/pkg/chains/solana/proto_helpers.go @@ -12,15 +12,14 @@ import ( codecpb "github.com/smartcontractkit/chainlink-common/pkg/internal/codec" chaincommonpb "github.com/smartcontractkit/chainlink-common/pkg/loop/chain-common" "github.com/smartcontractkit/chainlink-common/pkg/types/chains/solana" - typesolana "github.com/smartcontractkit/chainlink-common/pkg/types/chains/solana" "github.com/smartcontractkit/chainlink-common/pkg/types/query" "github.com/smartcontractkit/chainlink-common/pkg/types/query/primitives" solprimitives "github.com/smartcontractkit/chainlink-common/pkg/types/query/primitives/solana" valuespb "github.com/smartcontractkit/chainlink-protos/cre/go/values/pb" ) -func ConvertPublicKeysFromProto(pubKeys [][]byte) ([]typesolana.PublicKey, error) { - out := make([]typesolana.PublicKey, 0, len(pubKeys)) +func ConvertPublicKeysFromProto(pubKeys [][]byte) ([]solana.PublicKey, error) { + out := make([]solana.PublicKey, 0, len(pubKeys)) var errs []error for i, b := range pubKeys { pk, err := ConvertPublicKeyFromProto(b) @@ -36,35 +35,35 @@ func ConvertPublicKeysFromProto(pubKeys [][]byte) ([]typesolana.PublicKey, error return out, nil } -func ConvertPublicKeyFromProto(b []byte) (typesolana.PublicKey, error) { +func ConvertPublicKeyFromProto(b []byte) (solana.PublicKey, error) { if err := ValidatePublicKeyBytes(b); err != nil { - return typesolana.PublicKey{}, err + return solana.PublicKey{}, err } - return typesolana.PublicKey(b), nil + return solana.PublicKey(b), nil } func ValidatePublicKeyBytes(b []byte) error { if b == nil { return fmt.Errorf("address can't be nil") } - if len(b) != typesolana.PublicKeyLength { + if len(b) != solana.PublicKeyLength { return fmt.Errorf("invalid public key: got %d bytes, expected %d, value=%s", - len(b), typesolana.PublicKeyLength, base58.Encode(b)) + len(b), solana.PublicKeyLength, base58.Encode(b)) } return nil } -func ConvertSignatureFromProto(b []byte) (typesolana.Signature, error) { +func ConvertSignatureFromProto(b []byte) (solana.Signature, error) { if err := ValidateSignatureBytes(b); err != nil { - return typesolana.Signature{}, err + return solana.Signature{}, err } - var s typesolana.Signature - copy(s[:], b[:typesolana.SignatureLength]) + var s solana.Signature + copy(s[:], b[:solana.SignatureLength]) return s, nil } -func ConvertSignaturesFromProto(arr [][]byte) ([]typesolana.Signature, error) { - out := make([]typesolana.Signature, 0, len(arr)) +func ConvertSignaturesFromProto(arr [][]byte) ([]solana.Signature, error) { + out := make([]solana.Signature, 0, len(arr)) var errs []error for i, b := range arr { s, err := ConvertSignatureFromProto(b) @@ -80,7 +79,7 @@ func ConvertSignaturesFromProto(arr [][]byte) ([]typesolana.Signature, error) { return out, nil } -func ConvertSignaturesToProto(sigs []typesolana.Signature) [][]byte { +func ConvertSignaturesToProto(sigs []solana.Signature) [][]byte { out := make([][]byte, 0, len(sigs)) for _, s := range sigs { out = append(out, s[:]) @@ -92,136 +91,136 @@ func ValidateSignatureBytes(b []byte) error { if b == nil { return fmt.Errorf("signature can't be nil") } - if len(b) != typesolana.SignatureLength { + if len(b) != solana.SignatureLength { return fmt.Errorf("invalid signature: got %d bytes, expected %d, value=%s", - len(b), typesolana.SignatureLength, base58.Encode(b)) + len(b), solana.SignatureLength, base58.Encode(b)) } return nil } -func ConvertHashFromProto(b []byte) (typesolana.Hash, error) { +func ConvertHashFromProto(b []byte) (solana.Hash, error) { if b == nil { - return typesolana.Hash{}, fmt.Errorf("hash can't be nil") + return solana.Hash{}, fmt.Errorf("hash can't be nil") } if len(b) != solana.HashLength { - return typesolana.Hash{}, fmt.Errorf("invalid hash: got %d bytes, expected %d, value=%s", + return solana.Hash{}, fmt.Errorf("invalid hash: got %d bytes, expected %d, value=%s", len(b), solana.HashLength, base58.Encode(b)) } - return typesolana.Hash(typesolana.PublicKey(b)), nil + return solana.Hash(solana.PublicKey(b)), nil } -func ConvertEventSigFromProto(b []byte) (typesolana.EventSignature, error) { +func ConvertEventSigFromProto(b []byte) (solana.EventSignature, error) { if b == nil { - return typesolana.EventSignature{}, fmt.Errorf("hash can't be nil") + return solana.EventSignature{}, fmt.Errorf("hash can't be nil") } if len(b) != solana.EventSignatureLength { - return typesolana.EventSignature{}, fmt.Errorf("invalid event signature: got %d bytes, expected %d, value=%x", + return solana.EventSignature{}, fmt.Errorf("invalid event signature: got %d bytes, expected %d, value=%x", len(b), solana.EventSignatureLength, b) } - return typesolana.EventSignature(b), nil + return solana.EventSignature(b), nil } -func ConvertEncodingTypeFromProto(e EncodingType) typesolana.EncodingType { +func ConvertEncodingTypeFromProto(e EncodingType) solana.EncodingType { switch e { case EncodingType_ENCODING_TYPE_BASE58: - return typesolana.EncodingBase58 + return solana.EncodingBase58 case EncodingType_ENCODING_TYPE_BASE64: - return typesolana.EncodingBase64 + return solana.EncodingBase64 case EncodingType_ENCODING_TYPE_BASE64_ZSTD: - return typesolana.EncodingBase64Zstd + return solana.EncodingBase64Zstd case EncodingType_ENCODING_TYPE_JSON: - return typesolana.EncodingJSON + return solana.EncodingJSON case EncodingType_ENCODING_TYPE_JSON_PARSED: - return typesolana.EncodingJSONParsed + return solana.EncodingJSONParsed default: - return typesolana.EncodingType("") + return solana.EncodingType("") } } -func ConvertEncodingTypeToProto(e typesolana.EncodingType) EncodingType { +func ConvertEncodingTypeToProto(e solana.EncodingType) EncodingType { switch e { - case typesolana.EncodingBase64: + case solana.EncodingBase64: return EncodingType_ENCODING_TYPE_BASE64 - case typesolana.EncodingBase58: + case solana.EncodingBase58: return EncodingType_ENCODING_TYPE_BASE58 - case typesolana.EncodingBase64Zstd: + case solana.EncodingBase64Zstd: return EncodingType_ENCODING_TYPE_BASE64_ZSTD - case typesolana.EncodingJSONParsed: + case solana.EncodingJSONParsed: return EncodingType_ENCODING_TYPE_JSON_PARSED - case typesolana.EncodingJSON: + case solana.EncodingJSON: return EncodingType_ENCODING_TYPE_JSON default: return EncodingType_ENCODING_TYPE_NONE } } -func ConvertCommitmentFromProto(c CommitmentType) typesolana.CommitmentType { +func ConvertCommitmentFromProto(c CommitmentType) solana.CommitmentType { switch c { case CommitmentType_COMMITMENT_TYPE_CONFIRMED: - return typesolana.CommitmentConfirmed + return solana.CommitmentConfirmed case CommitmentType_COMMITMENT_TYPE_FINALIZED: - return typesolana.CommitmentFinalized + return solana.CommitmentFinalized case CommitmentType_COMMITMENT_TYPE_PROCESSED: - return typesolana.CommitmentProcessed + return solana.CommitmentProcessed default: - return typesolana.CommitmentType("") + return solana.CommitmentType("") } } -func ConvertCommitmentToProto(c typesolana.CommitmentType) CommitmentType { +func ConvertCommitmentToProto(c solana.CommitmentType) CommitmentType { switch c { - case typesolana.CommitmentFinalized: + case solana.CommitmentFinalized: return CommitmentType_COMMITMENT_TYPE_FINALIZED - case typesolana.CommitmentConfirmed: + case solana.CommitmentConfirmed: return CommitmentType_COMMITMENT_TYPE_CONFIRMED - case typesolana.CommitmentProcessed: + case solana.CommitmentProcessed: return CommitmentType_COMMITMENT_TYPE_PROCESSED default: return CommitmentType_COMMITMENT_TYPE_NONE } } -func ConvertConfirmationStatusToProto(c typesolana.ConfirmationStatusType) ConfirmationStatusType { +func ConvertConfirmationStatusToProto(c solana.ConfirmationStatusType) ConfirmationStatusType { switch c { - case typesolana.ConfirmationStatusFinalized: + case solana.ConfirmationStatusFinalized: return ConfirmationStatusType_CONFIRMATION_STATUS_TYPE_FINALIZED - case typesolana.ConfirmationStatusConfirmed: + case solana.ConfirmationStatusConfirmed: return ConfirmationStatusType_CONFIRMATION_STATUS_TYPE_CONFIRMED - case typesolana.ConfirmationStatusProcessed: + case solana.ConfirmationStatusProcessed: return ConfirmationStatusType_CONFIRMATION_STATUS_TYPE_PROCESSED default: return ConfirmationStatusType_CONFIRMATION_STATUS_TYPE_NONE } } -func ConvertConfirmationStatusFromProto(c ConfirmationStatusType) typesolana.ConfirmationStatusType { +func ConvertConfirmationStatusFromProto(c ConfirmationStatusType) solana.ConfirmationStatusType { switch c { case ConfirmationStatusType_CONFIRMATION_STATUS_TYPE_CONFIRMED: - return typesolana.ConfirmationStatusConfirmed + return solana.ConfirmationStatusConfirmed case ConfirmationStatusType_CONFIRMATION_STATUS_TYPE_FINALIZED: - return typesolana.ConfirmationStatusFinalized + return solana.ConfirmationStatusFinalized case ConfirmationStatusType_CONFIRMATION_STATUS_TYPE_PROCESSED: - return typesolana.ConfirmationStatusProcessed + return solana.ConfirmationStatusProcessed default: - return typesolana.ConfirmationStatusType("") + return solana.ConfirmationStatusType("") } } -func ConvertDataSliceFromProto(p *DataSlice) *typesolana.DataSlice { +func ConvertDataSliceFromProto(p *DataSlice) *solana.DataSlice { if p == nil { return nil } - return &typesolana.DataSlice{ + return &solana.DataSlice{ Offset: ptrUint64(p.Offset), Length: ptrUint64(p.Length), } } -func ConvertDataSliceToProto(d *typesolana.DataSlice) *DataSlice { +func ConvertDataSliceToProto(d *solana.DataSlice) *DataSlice { if d == nil { return nil } @@ -238,18 +237,18 @@ func ConvertDataSliceToProto(d *typesolana.DataSlice) *DataSlice { } } -func ConvertUiTokenAmountFromProto(p *UiTokenAmount) *typesolana.UiTokenAmount { +func ConvertUiTokenAmountFromProto(p *UiTokenAmount) *solana.UiTokenAmount { if p == nil { return nil } - return &typesolana.UiTokenAmount{ + return &solana.UiTokenAmount{ Amount: p.Amount, Decimals: uint8(p.Decimals), UiAmountString: p.UiAmountString, } } -func ConvertUiTokenAmountToProto(u *typesolana.UiTokenAmount) *UiTokenAmount { +func ConvertUiTokenAmountToProto(u *solana.UiTokenAmount) *UiTokenAmount { if u == nil { return nil } @@ -260,7 +259,7 @@ func ConvertUiTokenAmountToProto(u *typesolana.UiTokenAmount) *UiTokenAmount { } } -func ConvertAccountFromProto(p *Account) (*typesolana.Account, error) { +func ConvertAccountFromProto(p *Account) (*solana.Account, error) { if p == nil { return nil, nil } @@ -270,7 +269,7 @@ func ConvertAccountFromProto(p *Account) (*typesolana.Account, error) { } data := ConvertDataBytesOrJSONFromProto(p.Data) - return &typesolana.Account{ + return &solana.Account{ Lamports: p.Lamports, Owner: owner, Data: data, @@ -280,7 +279,7 @@ func ConvertAccountFromProto(p *Account) (*typesolana.Account, error) { }, nil } -func ConvertAccountToProto(a *typesolana.Account) *Account { +func ConvertAccountToProto(a *solana.Account) *Account { if a == nil { return nil } @@ -294,18 +293,18 @@ func ConvertAccountToProto(a *typesolana.Account) *Account { } } -func ConvertDataBytesOrJSONFromProto(p *DataBytesOrJSON) *typesolana.DataBytesOrJSON { +func ConvertDataBytesOrJSONFromProto(p *DataBytesOrJSON) *solana.DataBytesOrJSON { if p == nil { return nil } switch t := p.GetBody().(type) { case *DataBytesOrJSON_Raw: - return &typesolana.DataBytesOrJSON{ + return &solana.DataBytesOrJSON{ AsDecodedBinary: t.Raw, RawDataEncoding: ConvertEncodingTypeFromProto(p.Encoding), } case *DataBytesOrJSON_Json: - return &typesolana.DataBytesOrJSON{ + return &solana.DataBytesOrJSON{ AsJSON: t.Json, RawDataEncoding: ConvertEncodingTypeFromProto(p.Encoding), } @@ -314,7 +313,7 @@ func ConvertDataBytesOrJSONFromProto(p *DataBytesOrJSON) *typesolana.DataBytesOr return nil } -func ConvertDataBytesOrJSONToProto(d *typesolana.DataBytesOrJSON) *DataBytesOrJSON { +func ConvertDataBytesOrJSONToProto(d *solana.DataBytesOrJSON) *DataBytesOrJSON { if d == nil { return nil } @@ -332,11 +331,11 @@ func ConvertDataBytesOrJSONToProto(d *typesolana.DataBytesOrJSON) *DataBytesOrJS return ret } -func ConvertGetAccountInfoOptsFromProto(p *GetAccountInfoOpts) *typesolana.GetAccountInfoOpts { +func ConvertGetAccountInfoOptsFromProto(p *GetAccountInfoOpts) *solana.GetAccountInfoOpts { if p == nil { return nil } - return &typesolana.GetAccountInfoOpts{ + return &solana.GetAccountInfoOpts{ Encoding: ConvertEncodingTypeFromProto(p.Encoding), Commitment: ConvertCommitmentFromProto(p.Commitment), DataSlice: ConvertDataSliceFromProto(p.DataSlice), @@ -344,7 +343,7 @@ func ConvertGetAccountInfoOptsFromProto(p *GetAccountInfoOpts) *typesolana.GetAc } } -func ConvertGetAccountInfoOptsToProto(o *typesolana.GetAccountInfoOpts) *GetAccountInfoOpts { +func ConvertGetAccountInfoOptsToProto(o *solana.GetAccountInfoOpts) *GetAccountInfoOpts { if o == nil { return nil } @@ -360,11 +359,11 @@ func ConvertGetAccountInfoOptsToProto(o *typesolana.GetAccountInfoOpts) *GetAcco } } -func ConvertGetMultipleAccountsOptsFromProto(p *GetMultipleAccountsOpts) *typesolana.GetMultipleAccountsOpts { +func ConvertGetMultipleAccountsOptsFromProto(p *GetMultipleAccountsOpts) *solana.GetMultipleAccountsOpts { if p == nil { return nil } - return &typesolana.GetMultipleAccountsOpts{ + return &solana.GetMultipleAccountsOpts{ Encoding: ConvertEncodingTypeFromProto(p.Encoding), Commitment: ConvertCommitmentFromProto(p.Commitment), DataSlice: ConvertDataSliceFromProto(p.DataSlice), @@ -372,7 +371,7 @@ func ConvertGetMultipleAccountsOptsFromProto(p *GetMultipleAccountsOpts) *typeso } } -func ConvertGetMultipleAccountsOptsToProto(o *typesolana.GetMultipleAccountsOpts) *GetMultipleAccountsOpts { +func ConvertGetMultipleAccountsOptsToProto(o *solana.GetMultipleAccountsOpts) *GetMultipleAccountsOpts { if o == nil { return nil } @@ -388,16 +387,16 @@ func ConvertGetMultipleAccountsOptsToProto(o *typesolana.GetMultipleAccountsOpts } } -func ConvertGetBlockOptsFromProto(p *GetBlockOpts) *typesolana.GetBlockOpts { +func ConvertGetBlockOptsFromProto(p *GetBlockOpts) *solana.GetBlockOpts { if p == nil { return nil } - return &typesolana.GetBlockOpts{ + return &solana.GetBlockOpts{ Commitment: ConvertCommitmentFromProto(p.Commitment), } } -func ConvertGetBlockOptsToProto(o *typesolana.GetBlockOpts) *GetBlockOpts { +func ConvertGetBlockOptsToProto(o *solana.GetBlockOpts) *GetBlockOpts { if o == nil { return nil } @@ -406,18 +405,18 @@ func ConvertGetBlockOptsToProto(o *typesolana.GetBlockOpts) *GetBlockOpts { } } -func ConvertMessageHeaderFromProto(p *MessageHeader) typesolana.MessageHeader { +func ConvertMessageHeaderFromProto(p *MessageHeader) solana.MessageHeader { if p == nil { - return typesolana.MessageHeader{} + return solana.MessageHeader{} } - return typesolana.MessageHeader{ + return solana.MessageHeader{ NumRequiredSignatures: uint8(p.NumRequiredSignatures), NumReadonlySignedAccounts: uint8(p.NumReadonlySignedAccounts), NumReadonlyUnsignedAccounts: uint8(p.NumReadonlyUnsignedAccounts), } } -func ConvertMessageHeaderToProto(h typesolana.MessageHeader) *MessageHeader { +func ConvertMessageHeaderToProto(h solana.MessageHeader) *MessageHeader { return &MessageHeader{ NumRequiredSignatures: uint32(h.NumRequiredSignatures), NumReadonlySignedAccounts: uint32(h.NumReadonlySignedAccounts), @@ -425,16 +424,16 @@ func ConvertMessageHeaderToProto(h typesolana.MessageHeader) *MessageHeader { } } -func ConvertCompiledInstructionFromProto(p *CompiledInstruction) typesolana.CompiledInstruction { +func ConvertCompiledInstructionFromProto(p *CompiledInstruction) solana.CompiledInstruction { if p == nil { - return typesolana.CompiledInstruction{} + return solana.CompiledInstruction{} } accts := make([]uint16, len(p.Accounts)) for i, a := range p.Accounts { accts[i] = uint16(a) } - return typesolana.CompiledInstruction{ + return solana.CompiledInstruction{ ProgramIDIndex: uint16(p.ProgramIdIndex), Accounts: accts, Data: p.Data, @@ -442,7 +441,7 @@ func ConvertCompiledInstructionFromProto(p *CompiledInstruction) typesolana.Comp } } -func ConvertCompiledInstructionToProto(ci typesolana.CompiledInstruction) *CompiledInstruction { +func ConvertCompiledInstructionToProto(ci solana.CompiledInstruction) *CompiledInstruction { accts := make([]uint32, len(ci.Accounts)) for i, a := range ci.Accounts { accts[i] = uint32(a) @@ -455,13 +454,13 @@ func ConvertCompiledInstructionToProto(ci typesolana.CompiledInstruction) *Compi } } -func ConvertInnerInstructionFromProto(p *InnerInstruction) typesolana.InnerInstruction { +func ConvertInnerInstructionFromProto(p *InnerInstruction) solana.InnerInstruction { if p == nil { - return typesolana.InnerInstruction{} + return solana.InnerInstruction{} } - out := typesolana.InnerInstruction{ + out := solana.InnerInstruction{ Index: uint16(p.Index), - Instructions: make([]typesolana.CompiledInstruction, 0, len(p.Instructions)), + Instructions: make([]solana.CompiledInstruction, 0, len(p.Instructions)), } for _, in := range p.Instructions { out.Instructions = append(out.Instructions, ConvertCompiledInstructionFromProto(in)) @@ -469,7 +468,7 @@ func ConvertInnerInstructionFromProto(p *InnerInstruction) typesolana.InnerInstr return out } -func ConvertInnerInstructionToProto(ii typesolana.InnerInstruction) *InnerInstruction { +func ConvertInnerInstructionToProto(ii solana.InnerInstruction) *InnerInstruction { out := &InnerInstruction{ Index: uint32(ii.Index), Instructions: make([]*CompiledInstruction, 0, len(ii.Instructions)), @@ -480,26 +479,26 @@ func ConvertInnerInstructionToProto(ii typesolana.InnerInstruction) *InnerInstru return out } -func ConvertLoadedAddressesFromProto(p *LoadedAddresses) typesolana.LoadedAddresses { +func ConvertLoadedAddressesFromProto(p *LoadedAddresses) solana.LoadedAddresses { if p == nil { - return typesolana.LoadedAddresses{} + return solana.LoadedAddresses{} } ro, _ := ConvertPublicKeysFromProto(p.Readonly) wr, _ := ConvertPublicKeysFromProto(p.Writable) - return typesolana.LoadedAddresses{ + return solana.LoadedAddresses{ ReadOnly: ro, Writable: wr, } } -func ConvertLoadedAddressesToProto(l typesolana.LoadedAddresses) *LoadedAddresses { +func ConvertLoadedAddressesToProto(l solana.LoadedAddresses) *LoadedAddresses { return &LoadedAddresses{ Readonly: ConvertPublicKeysToProto(l.ReadOnly), Writable: ConvertPublicKeysToProto(l.Writable), } } -func ConvertPublicKeysToProto(keys []typesolana.PublicKey) [][]byte { +func ConvertPublicKeysToProto(keys []solana.PublicKey) [][]byte { out := make([][]byte, 0, len(keys)) for _, k := range keys { out = append(out, k[:]) @@ -507,23 +506,23 @@ func ConvertPublicKeysToProto(keys []typesolana.PublicKey) [][]byte { return out } -func ConvertParsedMessageFromProto(p *ParsedMessage) (typesolana.Message, error) { +func ConvertParsedMessageFromProto(p *ParsedMessage) (solana.Message, error) { if p == nil { - return typesolana.Message{}, nil + return solana.Message{}, nil } rb, err := ConvertHashFromProto(p.RecentBlockhash) if err != nil { - return typesolana.Message{}, fmt.Errorf("recent blockhash: %w", err) + return solana.Message{}, fmt.Errorf("recent blockhash: %w", err) } keys, err := ConvertPublicKeysFromProto(p.AccountKeys) if err != nil { - return typesolana.Message{}, fmt.Errorf("account keys: %w", err) + return solana.Message{}, fmt.Errorf("account keys: %w", err) } - msg := typesolana.Message{ + msg := solana.Message{ AccountKeys: keys, Header: ConvertMessageHeaderFromProto(p.Header), RecentBlockhash: rb, - Instructions: make([]typesolana.CompiledInstruction, 0, len(p.Instructions)), + Instructions: make([]solana.CompiledInstruction, 0, len(p.Instructions)), } for _, ins := range p.Instructions { msg.Instructions = append(msg.Instructions, ConvertCompiledInstructionFromProto(ins)) @@ -531,7 +530,7 @@ func ConvertParsedMessageFromProto(p *ParsedMessage) (typesolana.Message, error) return msg, nil } -func ConvertParsedMessageToProto(m typesolana.Message) *ParsedMessage { +func ConvertParsedMessageToProto(m solana.Message) *ParsedMessage { out := &ParsedMessage{ RecentBlockhash: m.RecentBlockhash[:], AccountKeys: ConvertPublicKeysToProto(m.AccountKeys), @@ -544,32 +543,32 @@ func ConvertParsedMessageToProto(m typesolana.Message) *ParsedMessage { return out } -func ConvertParsedTransactionFromProto(p *ParsedTransaction) (typesolana.Transaction, error) { +func ConvertParsedTransactionFromProto(p *ParsedTransaction) (solana.Transaction, error) { if p == nil { - return typesolana.Transaction{}, nil + return solana.Transaction{}, nil } sigs, err := ConvertSignaturesFromProto(p.Signatures) if err != nil { - return typesolana.Transaction{}, fmt.Errorf("signatures: %w", err) + return solana.Transaction{}, fmt.Errorf("signatures: %w", err) } msg, err := ConvertParsedMessageFromProto(p.Message) if err != nil { - return typesolana.Transaction{}, fmt.Errorf("message: %w", err) + return solana.Transaction{}, fmt.Errorf("message: %w", err) } - return typesolana.Transaction{ + return solana.Transaction{ Signatures: sigs, Message: msg, }, nil } -func ConvertParsedTransactionToProto(t typesolana.Transaction) *ParsedTransaction { +func ConvertParsedTransactionToProto(t solana.Transaction) *ParsedTransaction { return &ParsedTransaction{ Signatures: ConvertSignaturesToProto(t.Signatures), Message: ConvertParsedMessageToProto(t.Message), } } -func ConvertTokenBalanceFromProto(p *TokenBalance) (*typesolana.TokenBalance, error) { +func ConvertTokenBalanceFromProto(p *TokenBalance) (*solana.TokenBalance, error) { if p == nil { return nil, nil } @@ -577,7 +576,7 @@ func ConvertTokenBalanceFromProto(p *TokenBalance) (*typesolana.TokenBalance, er if err != nil { return nil, fmt.Errorf("mint: %w", err) } - var owner *typesolana.PublicKey + var owner *solana.PublicKey if len(p.Owner) > 0 { o, err := ConvertPublicKeyFromProto(p.Owner) if err != nil { @@ -585,7 +584,7 @@ func ConvertTokenBalanceFromProto(p *TokenBalance) (*typesolana.TokenBalance, er } owner = &o } - var program *typesolana.PublicKey + var program *solana.PublicKey if len(p.ProgramId) > 0 { prog, err := ConvertPublicKeyFromProto(p.ProgramId) if err != nil { @@ -593,7 +592,7 @@ func ConvertTokenBalanceFromProto(p *TokenBalance) (*typesolana.TokenBalance, er } program = &prog } - return &typesolana.TokenBalance{ + return &solana.TokenBalance{ AccountIndex: uint16(p.AccountIndex), Owner: owner, ProgramId: program, @@ -602,7 +601,7 @@ func ConvertTokenBalanceFromProto(p *TokenBalance) (*typesolana.TokenBalance, er }, nil } -func ConvertTokenBalanceToProto(tb *typesolana.TokenBalance) *TokenBalance { +func ConvertTokenBalanceToProto(tb *solana.TokenBalance) *TokenBalance { if tb == nil { return nil } @@ -624,7 +623,7 @@ func ConvertTokenBalanceToProto(tb *typesolana.TokenBalance) *TokenBalance { } } -func ConvertReturnDataFromProto(p *ReturnData) (*typesolana.ReturnData, error) { +func ConvertReturnDataFromProto(p *ReturnData) (*solana.ReturnData, error) { if p == nil { return nil, nil } @@ -632,16 +631,16 @@ func ConvertReturnDataFromProto(p *ReturnData) (*typesolana.ReturnData, error) { if err != nil { return nil, fmt.Errorf("programId: %w", err) } - return &typesolana.ReturnData{ + return &solana.ReturnData{ ProgramId: prog, - Data: typesolana.Data{ + Data: solana.Data{ Content: p.Data.GetContent(), Encoding: ConvertEncodingTypeFromProto(p.Data.GetEncoding()), }, }, nil } -func ConvertReturnDataToProto(r *typesolana.ReturnData) *ReturnData { +func ConvertReturnDataToProto(r *solana.ReturnData) *ReturnData { if r == nil { return nil } @@ -655,11 +654,11 @@ func ConvertReturnDataToProto(r *typesolana.ReturnData) *ReturnData { } } -func ConvertTransactionMetaFromProto(p *TransactionMeta) (*typesolana.TransactionMeta, error) { +func ConvertTransactionMetaFromProto(p *TransactionMeta) (*solana.TransactionMeta, error) { if p == nil { return nil, nil } - preTB := make([]typesolana.TokenBalance, 0, len(p.PreTokenBalances)) + preTB := make([]solana.TokenBalance, 0, len(p.PreTokenBalances)) for _, x := range p.PreTokenBalances { tb, err := ConvertTokenBalanceFromProto(x) if err != nil { @@ -667,7 +666,7 @@ func ConvertTransactionMetaFromProto(p *TransactionMeta) (*typesolana.Transactio } preTB = append(preTB, *tb) } - postTB := make([]typesolana.TokenBalance, 0, len(p.PostTokenBalances)) + postTB := make([]solana.TokenBalance, 0, len(p.PostTokenBalances)) for _, x := range p.PostTokenBalances { tb, err := ConvertTokenBalanceFromProto(x) if err != nil { @@ -675,7 +674,7 @@ func ConvertTransactionMetaFromProto(p *TransactionMeta) (*typesolana.Transactio } postTB = append(postTB, *tb) } - inner := make([]typesolana.InnerInstruction, 0, len(p.InnerInstructions)) + inner := make([]solana.InnerInstruction, 0, len(p.InnerInstructions)) for _, in := range p.InnerInstructions { inner = append(inner, ConvertInnerInstructionFromProto(in)) } @@ -685,7 +684,7 @@ func ConvertTransactionMetaFromProto(p *TransactionMeta) (*typesolana.Transactio } la := ConvertLoadedAddressesFromProto(p.LoadedAddresses) - meta := &typesolana.TransactionMeta{ + meta := &solana.TransactionMeta{ Err: p.ErrJson, Fee: p.Fee, PreBalances: p.PreBalances, @@ -701,7 +700,7 @@ func ConvertTransactionMetaFromProto(p *TransactionMeta) (*typesolana.Transactio return meta, nil } -func ConvertTransactionMetaToProto(m *typesolana.TransactionMeta) *TransactionMeta { +func ConvertTransactionMetaToProto(m *solana.TransactionMeta) *TransactionMeta { if m == nil { return nil } @@ -736,21 +735,21 @@ func ConvertTransactionMetaToProto(m *typesolana.TransactionMeta) *TransactionMe } } -func ConvertTransactionEnvelopeFromProto(p *TransactionEnvelope) (typesolana.TransactionResultEnvelope, error) { +func ConvertTransactionEnvelopeFromProto(p *TransactionEnvelope) (solana.TransactionResultEnvelope, error) { if p == nil { - return typesolana.TransactionResultEnvelope{}, nil + return solana.TransactionResultEnvelope{}, nil } - var out typesolana.TransactionResultEnvelope + var out solana.TransactionResultEnvelope switch t := p.GetTransaction().(type) { case *TransactionEnvelope_Raw: - out.AsDecodedBinary = typesolana.Data{ + out.AsDecodedBinary = solana.Data{ Content: t.Raw, - Encoding: typesolana.EncodingBase64, + Encoding: solana.EncodingBase64, } case *TransactionEnvelope_Parsed: ptx, err := ConvertParsedTransactionFromProto(t.Parsed) if err != nil { - return typesolana.TransactionResultEnvelope{}, err + return solana.TransactionResultEnvelope{}, err } out.AsParsedTransaction = &ptx default: @@ -758,7 +757,7 @@ func ConvertTransactionEnvelopeFromProto(p *TransactionEnvelope) (typesolana.Tra return out, nil } -func ConvertTransactionEnvelopeToProto(e typesolana.TransactionResultEnvelope) *TransactionEnvelope { +func ConvertTransactionEnvelopeToProto(e solana.TransactionResultEnvelope) *TransactionEnvelope { switch { case e.AsParsedTransaction != nil: return &TransactionEnvelope{ @@ -777,7 +776,7 @@ func ConvertTransactionEnvelopeToProto(e typesolana.TransactionResultEnvelope) * } } -func ConvertGetTransactionReplyFromProto(p *GetTransactionReply) (*typesolana.GetTransactionReply, error) { +func ConvertGetTransactionReplyFromProto(p *GetTransactionReply) (*solana.GetTransactionReply, error) { if p == nil { return nil, nil } @@ -789,12 +788,12 @@ func ConvertGetTransactionReplyFromProto(p *GetTransactionReply) (*typesolana.Ge if err != nil { return nil, err } - var bt *typesolana.UnixTimeSeconds + var bt *solana.UnixTimeSeconds if p.BlockTime != nil { - bt = ptrUnix(typesolana.UnixTimeSeconds(*p.BlockTime)) + bt = ptrUnix(solana.UnixTimeSeconds(*p.BlockTime)) } - return &typesolana.GetTransactionReply{ + return &solana.GetTransactionReply{ Slot: p.Slot, BlockTime: bt, Transaction: &env, @@ -802,7 +801,7 @@ func ConvertGetTransactionReplyFromProto(p *GetTransactionReply) (*typesolana.Ge }, nil } -func ConvertGetTransactionReplyToProto(r *typesolana.GetTransactionReply) *GetTransactionReply { +func ConvertGetTransactionReplyToProto(r *solana.GetTransactionReply) *GetTransactionReply { if r == nil { return nil } @@ -822,73 +821,73 @@ func ConvertGetTransactionReplyToProto(r *typesolana.GetTransactionReply) *GetTr } } -func ConvertGetTransactionRequestFromProto(p *GetTransactionRequest) (typesolana.GetTransactionRequest, error) { +func ConvertGetTransactionRequestFromProto(p *GetTransactionRequest) (solana.GetTransactionRequest, error) { sig, err := ConvertSignatureFromProto(p.Signature) if err != nil { - return typesolana.GetTransactionRequest{}, err + return solana.GetTransactionRequest{}, err } - return typesolana.GetTransactionRequest{Signature: sig}, nil + return solana.GetTransactionRequest{Signature: sig}, nil } -func ConvertGetTransactionRequestToProto(r typesolana.GetTransactionRequest) *GetTransactionRequest { +func ConvertGetTransactionRequestToProto(r solana.GetTransactionRequest) *GetTransactionRequest { return &GetTransactionRequest{Signature: r.Signature[:]} } -func ConvertGetBalanceReplyFromProto(p *GetBalanceReply) *typesolana.GetBalanceReply { +func ConvertGetBalanceReplyFromProto(p *GetBalanceReply) *solana.GetBalanceReply { if p == nil { return nil } - return &typesolana.GetBalanceReply{Value: p.Value} + return &solana.GetBalanceReply{Value: p.Value} } -func ConvertGetBalanceReplyToProto(r *typesolana.GetBalanceReply) *GetBalanceReply { +func ConvertGetBalanceReplyToProto(r *solana.GetBalanceReply) *GetBalanceReply { if r == nil { return nil } return &GetBalanceReply{Value: r.Value} } -func ConvertGetBalanceRequestFromProto(p *GetBalanceRequest) (typesolana.GetBalanceRequest, error) { +func ConvertGetBalanceRequestFromProto(p *GetBalanceRequest) (solana.GetBalanceRequest, error) { pk, err := ConvertPublicKeyFromProto(p.Addr) if err != nil { - return typesolana.GetBalanceRequest{}, err + return solana.GetBalanceRequest{}, err } - return typesolana.GetBalanceRequest{ + return solana.GetBalanceRequest{ Addr: pk, Commitment: ConvertCommitmentFromProto(p.Commitment), }, nil } -func ConvertGetBalanceRequestToProto(r typesolana.GetBalanceRequest) *GetBalanceRequest { +func ConvertGetBalanceRequestToProto(r solana.GetBalanceRequest) *GetBalanceRequest { return &GetBalanceRequest{ Addr: r.Addr[:], Commitment: ConvertCommitmentToProto(r.Commitment), } } -func ConvertGetSlotHeightReplyFromProto(p *GetSlotHeightReply) *typesolana.GetSlotHeightReply { +func ConvertGetSlotHeightReplyFromProto(p *GetSlotHeightReply) *solana.GetSlotHeightReply { if p == nil { return nil } - return &typesolana.GetSlotHeightReply{Height: p.Height} + return &solana.GetSlotHeightReply{Height: p.Height} } -func ConvertGetSlotHeightReplyToProto(r *typesolana.GetSlotHeightReply) *GetSlotHeightReply { +func ConvertGetSlotHeightReplyToProto(r *solana.GetSlotHeightReply) *GetSlotHeightReply { if r == nil { return nil } return &GetSlotHeightReply{Height: r.Height} } -func ConvertGetSlotHeightRequestFromProto(p *GetSlotHeightRequest) typesolana.GetSlotHeightRequest { - return typesolana.GetSlotHeightRequest{Commitment: ConvertCommitmentFromProto(p.Commitment)} +func ConvertGetSlotHeightRequestFromProto(p *GetSlotHeightRequest) solana.GetSlotHeightRequest { + return solana.GetSlotHeightRequest{Commitment: ConvertCommitmentFromProto(p.Commitment)} } -func ConvertGetSlotHeightRequestToProto(r typesolana.GetSlotHeightRequest) *GetSlotHeightRequest { +func ConvertGetSlotHeightRequestToProto(r solana.GetSlotHeightRequest) *GetSlotHeightRequest { return &GetSlotHeightRequest{Commitment: ConvertCommitmentToProto(r.Commitment)} } -func ConvertGetBlockOptsReplyFromProto(p *GetBlockReply) (*typesolana.GetBlockReply, error) { +func ConvertGetBlockOptsReplyFromProto(p *GetBlockReply) (*solana.GetBlockReply, error) { if p == nil { return nil, nil } @@ -903,10 +902,10 @@ func ConvertGetBlockOptsReplyFromProto(p *GetBlockReply) (*typesolana.GetBlockRe var bt *solana.UnixTimeSeconds if p.BlockTime != nil { - bt = ptrUnix(typesolana.UnixTimeSeconds(*p.BlockTime)) + bt = ptrUnix(solana.UnixTimeSeconds(*p.BlockTime)) } - return &typesolana.GetBlockReply{ + return &solana.GetBlockReply{ Blockhash: hash, PreviousBlockhash: prev, ParentSlot: p.ParentSlot, @@ -915,7 +914,7 @@ func ConvertGetBlockOptsReplyFromProto(p *GetBlockReply) (*typesolana.GetBlockRe }, nil } -func ConvertGetBlockReplyToProto(r *typesolana.GetBlockReply) *GetBlockReply { +func ConvertGetBlockReplyToProto(r *solana.GetBlockReply) *GetBlockReply { if r == nil { return nil } @@ -938,17 +937,17 @@ func ConvertGetBlockReplyToProto(r *typesolana.GetBlockReply) *GetBlockReply { } } -func ConvertGetBlockRequestFromProto(p *GetBlockRequest) *typesolana.GetBlockRequest { +func ConvertGetBlockRequestFromProto(p *GetBlockRequest) *solana.GetBlockRequest { if p == nil { return nil } - return &typesolana.GetBlockRequest{ + return &solana.GetBlockRequest{ Slot: p.Slot, Opts: ConvertGetBlockOptsFromProto(p.Opts), } } -func ConvertGetBlockRequestToProto(r *typesolana.GetBlockRequest) *GetBlockRequest { +func ConvertGetBlockRequestToProto(r *solana.GetBlockRequest) *GetBlockRequest { if r == nil { return nil } @@ -958,17 +957,17 @@ func ConvertGetBlockRequestToProto(r *typesolana.GetBlockRequest) *GetBlockReque } } -func ConvertGetFeeForMessageRequestFromProto(p *GetFeeForMessageRequest) *typesolana.GetFeeForMessageRequest { +func ConvertGetFeeForMessageRequestFromProto(p *GetFeeForMessageRequest) *solana.GetFeeForMessageRequest { if p == nil { return nil } - return &typesolana.GetFeeForMessageRequest{ + return &solana.GetFeeForMessageRequest{ Message: p.Message, Commitment: ConvertCommitmentFromProto(p.Commitment), } } -func ConvertGetFeeForMessageRequestToProto(r *typesolana.GetFeeForMessageRequest) *GetFeeForMessageRequest { +func ConvertGetFeeForMessageRequestToProto(r *solana.GetFeeForMessageRequest) *GetFeeForMessageRequest { if r == nil { return nil } @@ -978,32 +977,32 @@ func ConvertGetFeeForMessageRequestToProto(r *typesolana.GetFeeForMessageRequest } } -func ConvertGetFeeForMessageReplyFromProto(p *GetFeeForMessageReply) *typesolana.GetFeeForMessageReply { +func ConvertGetFeeForMessageReplyFromProto(p *GetFeeForMessageReply) *solana.GetFeeForMessageReply { if p == nil { return nil } - return &typesolana.GetFeeForMessageReply{Fee: p.Fee} + return &solana.GetFeeForMessageReply{Fee: p.Fee} } -func ConvertGetFeeForMessageReplyToProto(r *typesolana.GetFeeForMessageReply) *GetFeeForMessageReply { +func ConvertGetFeeForMessageReplyToProto(r *solana.GetFeeForMessageReply) *GetFeeForMessageReply { if r == nil { return nil } return &GetFeeForMessageReply{Fee: r.Fee} } -func ConvertGetMultipleAccountsRequestFromProto(p *GetMultipleAccountsWithOptsRequest) *typesolana.GetMultipleAccountsRequest { +func ConvertGetMultipleAccountsRequestFromProto(p *GetMultipleAccountsWithOptsRequest) *solana.GetMultipleAccountsRequest { if p == nil { return nil } accts, _ := ConvertPublicKeysFromProto(p.Accounts) - return &typesolana.GetMultipleAccountsRequest{ + return &solana.GetMultipleAccountsRequest{ Accounts: accts, Opts: ConvertGetMultipleAccountsOptsFromProto(p.Opts), } } -func ConvertGetMultipleAccountsRequestToProto(r *typesolana.GetMultipleAccountsRequest) *GetMultipleAccountsWithOptsRequest { +func ConvertGetMultipleAccountsRequestToProto(r *solana.GetMultipleAccountsRequest) *GetMultipleAccountsWithOptsRequest { if r == nil { return nil } @@ -1013,11 +1012,11 @@ func ConvertGetMultipleAccountsRequestToProto(r *typesolana.GetMultipleAccountsR } } -func ConvertGetMultipleAccountsReplyFromProto(p *GetMultipleAccountsWithOptsReply) (*typesolana.GetMultipleAccountsReply, error) { +func ConvertGetMultipleAccountsReplyFromProto(p *GetMultipleAccountsWithOptsReply) (*solana.GetMultipleAccountsReply, error) { if p == nil { return nil, nil } - val := make([]*typesolana.Account, 0, len(p.Value)) + val := make([]*solana.Account, 0, len(p.Value)) for _, a := range p.Value { acc, err := ConvertAccountFromProto(a.Account) if err != nil { @@ -1025,12 +1024,12 @@ func ConvertGetMultipleAccountsReplyFromProto(p *GetMultipleAccountsWithOptsRepl } val = append(val, acc) } - return &typesolana.GetMultipleAccountsReply{ + return &solana.GetMultipleAccountsReply{ Value: val, }, nil } -func ConvertGetMultipleAccountsReplyToProto(r *typesolana.GetMultipleAccountsReply) *GetMultipleAccountsWithOptsReply { +func ConvertGetMultipleAccountsReplyToProto(r *solana.GetMultipleAccountsReply) *GetMultipleAccountsWithOptsReply { if r == nil { return nil } @@ -1044,7 +1043,7 @@ func ConvertGetMultipleAccountsReplyToProto(r *typesolana.GetMultipleAccountsRep } } -func ConvertGetSignatureStatusesRequestFromProto(p *GetSignatureStatusesRequest) (*typesolana.GetSignatureStatusesRequest, error) { +func ConvertGetSignatureStatusesRequestFromProto(p *GetSignatureStatusesRequest) (*solana.GetSignatureStatusesRequest, error) { if p == nil { return nil, nil } @@ -1052,23 +1051,23 @@ func ConvertGetSignatureStatusesRequestFromProto(p *GetSignatureStatusesRequest) if err != nil { return nil, err } - return &typesolana.GetSignatureStatusesRequest{Sigs: sigs}, nil + return &solana.GetSignatureStatusesRequest{Sigs: sigs}, nil } -func ConvertGetSignatureStatusesRequestToProto(r *typesolana.GetSignatureStatusesRequest) *GetSignatureStatusesRequest { +func ConvertGetSignatureStatusesRequestToProto(r *solana.GetSignatureStatusesRequest) *GetSignatureStatusesRequest { if r == nil { return nil } return &GetSignatureStatusesRequest{Sigs: ConvertSignaturesToProto(r.Sigs)} } -func ConvertGetSignatureStatusesReplyFromProto(p *GetSignatureStatusesReply) *typesolana.GetSignatureStatusesReply { +func ConvertGetSignatureStatusesReplyFromProto(p *GetSignatureStatusesReply) *solana.GetSignatureStatusesReply { if p == nil { return nil } - out := &typesolana.GetSignatureStatusesReply{Results: make([]typesolana.GetSignatureStatusesResult, 0, len(p.Results))} + out := &solana.GetSignatureStatusesReply{Results: make([]solana.GetSignatureStatusesResult, 0, len(p.Results))} for _, r := range p.Results { - out.Results = append(out.Results, typesolana.GetSignatureStatusesResult{ + out.Results = append(out.Results, solana.GetSignatureStatusesResult{ Slot: r.Slot, Confirmations: r.Confirmations, Err: r.Err, @@ -1078,7 +1077,7 @@ func ConvertGetSignatureStatusesReplyFromProto(p *GetSignatureStatusesReply) *ty return out } -func ConvertGetSignatureStatusesReplyToProto(r *typesolana.GetSignatureStatusesReply) *GetSignatureStatusesReply { +func ConvertGetSignatureStatusesReplyToProto(r *solana.GetSignatureStatusesReply) *GetSignatureStatusesReply { if r == nil { return nil } @@ -1098,18 +1097,18 @@ func ConvertGetSignatureStatusesReplyToProto(r *typesolana.GetSignatureStatusesR return out } -func ConvertSimulateTransactionAccountsOptsFromProto(p *SimulateTransactionAccountsOpts) *typesolana.SimulateTransactionAccountsOpts { +func ConvertSimulateTransactionAccountsOptsFromProto(p *SimulateTransactionAccountsOpts) *solana.SimulateTransactionAccountsOpts { if p == nil { return nil } addrs, _ := ConvertPublicKeysFromProto(p.Addresses) - return &typesolana.SimulateTransactionAccountsOpts{ + return &solana.SimulateTransactionAccountsOpts{ Encoding: ConvertEncodingTypeFromProto(p.Encoding), Addresses: addrs, } } -func ConvertSimulateTransactionAccountsOptsToProto(o *typesolana.SimulateTransactionAccountsOpts) *SimulateTransactionAccountsOpts { +func ConvertSimulateTransactionAccountsOptsToProto(o *solana.SimulateTransactionAccountsOpts) *SimulateTransactionAccountsOpts { if o == nil { return nil } @@ -1119,11 +1118,11 @@ func ConvertSimulateTransactionAccountsOptsToProto(o *typesolana.SimulateTransac } } -func ConvertSimulateTXOptsFromProto(p *SimulateTXOpts) *typesolana.SimulateTXOpts { +func ConvertSimulateTXOptsFromProto(p *SimulateTXOpts) *solana.SimulateTXOpts { if p == nil { return nil } - return &typesolana.SimulateTXOpts{ + return &solana.SimulateTXOpts{ SigVerify: p.SigVerify, Commitment: ConvertCommitmentFromProto(p.Commitment), ReplaceRecentBlockhash: p.ReplaceRecentBlockhash, @@ -1131,7 +1130,7 @@ func ConvertSimulateTXOptsFromProto(p *SimulateTXOpts) *typesolana.SimulateTXOpt } } -func ConvertSimulateTXOptsToProto(o *typesolana.SimulateTXOpts) *SimulateTXOpts { +func ConvertSimulateTXOptsToProto(o *solana.SimulateTXOpts) *SimulateTXOpts { if o == nil { return nil } @@ -1143,19 +1142,19 @@ func ConvertSimulateTXOptsToProto(o *typesolana.SimulateTXOpts) *SimulateTXOpts } } -func ConvertSimulateTXRequestFromProto(p *SimulateTXRequest) (typesolana.SimulateTXRequest, error) { +func ConvertSimulateTXRequestFromProto(p *SimulateTXRequest) (solana.SimulateTXRequest, error) { recv, err := ConvertPublicKeyFromProto(p.Receiver) if err != nil { - return typesolana.SimulateTXRequest{}, fmt.Errorf("receiver: %w", err) + return solana.SimulateTXRequest{}, fmt.Errorf("receiver: %w", err) } - return typesolana.SimulateTXRequest{ + return solana.SimulateTXRequest{ Receiver: recv, EncodedTransaction: p.EncodedTransaction, Opts: ConvertSimulateTXOptsFromProto(p.Opts), }, nil } -func ConvertSimulateTXRequestToProto(r typesolana.SimulateTXRequest) *SimulateTXRequest { +func ConvertSimulateTXRequestToProto(r solana.SimulateTXRequest) *SimulateTXRequest { return &SimulateTXRequest{ Receiver: r.Receiver[:], EncodedTransaction: r.EncodedTransaction, @@ -1163,11 +1162,11 @@ func ConvertSimulateTXRequestToProto(r typesolana.SimulateTXRequest) *SimulateTX } } -func ConvertSimulateTXReplyFromProto(p *SimulateTXReply) (*typesolana.SimulateTXReply, error) { +func ConvertSimulateTXReplyFromProto(p *SimulateTXReply) (*solana.SimulateTXReply, error) { if p == nil { return nil, nil } - accs := make([]*typesolana.Account, 0, len(p.Accounts)) + accs := make([]*solana.Account, 0, len(p.Accounts)) for _, a := range p.Accounts { acc, err := ConvertAccountFromProto(a) if err != nil { @@ -1175,7 +1174,7 @@ func ConvertSimulateTXReplyFromProto(p *SimulateTXReply) (*typesolana.SimulateTX } accs = append(accs, acc) } - return &typesolana.SimulateTXReply{ + return &solana.SimulateTXReply{ Err: p.Err, Logs: p.Logs, Accounts: accs, @@ -1183,7 +1182,7 @@ func ConvertSimulateTXReplyFromProto(p *SimulateTXReply) (*typesolana.SimulateTX }, nil } -func ConvertSimulateTXReplyToProto(r *typesolana.SimulateTXReply) *SimulateTXReply { +func ConvertSimulateTXReplyToProto(r *solana.SimulateTXReply) *SimulateTXReply { if r == nil { return nil } @@ -1202,17 +1201,17 @@ func ConvertSimulateTXReplyToProto(r *typesolana.SimulateTXReply) *SimulateTXRep return out } -func ConvertComputeConfigFromProto(p *ComputeConfig) *typesolana.ComputeConfig { +func ConvertComputeConfigFromProto(p *ComputeConfig) *solana.ComputeConfig { if p == nil { return nil } - return &typesolana.ComputeConfig{ + return &solana.ComputeConfig{ ComputeLimit: &p.ComputeLimit, ComputeMaxPrice: &p.ComputeMaxPrice, } } -func ConvertComputeConfigToProto(c *typesolana.ComputeConfig) *ComputeConfig { +func ConvertComputeConfigToProto(c *solana.ComputeConfig) *ComputeConfig { if c == nil { return nil } @@ -1231,22 +1230,22 @@ func ConvertComputeConfigToProto(c *typesolana.ComputeConfig) *ComputeConfig { } } -func ConvertSubmitTransactionRequestFromProto(p *SubmitTransactionRequest) (typesolana.SubmitTransactionRequest, error) { +func ConvertSubmitTransactionRequestFromProto(p *SubmitTransactionRequest) (solana.SubmitTransactionRequest, error) { if p == nil { - return typesolana.SubmitTransactionRequest{}, nil + return solana.SubmitTransactionRequest{}, nil } rcv, err := ConvertPublicKeyFromProto(p.Receiver) if err != nil { - return typesolana.SubmitTransactionRequest{}, fmt.Errorf("receiver: %w", err) + return solana.SubmitTransactionRequest{}, fmt.Errorf("receiver: %w", err) } - return typesolana.SubmitTransactionRequest{ + return solana.SubmitTransactionRequest{ Cfg: ConvertComputeConfigFromProto(p.Cfg), Receiver: rcv, EncodedTransaction: p.EncodedTransaction, }, nil } -func ConvertSubmitTransactionRequestToProto(r typesolana.SubmitTransactionRequest) *SubmitTransactionRequest { +func ConvertSubmitTransactionRequestToProto(r solana.SubmitTransactionRequest) *SubmitTransactionRequest { return &SubmitTransactionRequest{ Cfg: ConvertComputeConfigToProto(r.Cfg), Receiver: r.Receiver[:], @@ -1254,7 +1253,7 @@ func ConvertSubmitTransactionRequestToProto(r typesolana.SubmitTransactionReques } } -func ConvertSubmitTransactionReplyFromProto(p *SubmitTransactionReply) (*typesolana.SubmitTransactionReply, error) { +func ConvertSubmitTransactionReplyFromProto(p *SubmitTransactionReply) (*solana.SubmitTransactionReply, error) { if p == nil { return nil, nil } @@ -1262,14 +1261,14 @@ func ConvertSubmitTransactionReplyFromProto(p *SubmitTransactionReply) (*typesol if err != nil { return nil, err } - return &typesolana.SubmitTransactionReply{ + return &solana.SubmitTransactionReply{ Signature: sig, IdempotencyKey: p.IdempotencyKey, - Status: typesolana.TransactionStatus(p.Status), + Status: solana.TransactionStatus(p.Status), }, nil } -func ConvertSubmitTransactionReplyToProto(r *typesolana.SubmitTransactionReply) *SubmitTransactionReply { +func ConvertSubmitTransactionReplyToProto(r *solana.SubmitTransactionReply) *SubmitTransactionReply { if r == nil { return nil } @@ -1280,18 +1279,18 @@ func ConvertSubmitTransactionReplyToProto(r *typesolana.SubmitTransactionReply) } } -func ConvertRPCContextFromProto(p *RPCContext) typesolana.RPCContext { +func ConvertRPCContextFromProto(p *RPCContext) solana.RPCContext { if p == nil { - return typesolana.RPCContext{} + return solana.RPCContext{} } - return typesolana.RPCContext{Slot: p.Slot} + return solana.RPCContext{Slot: p.Slot} } -func ConvertRPCContextToProto(r typesolana.RPCContext) *RPCContext { +func ConvertRPCContextToProto(r solana.RPCContext) *RPCContext { return &RPCContext{Slot: r.Slot} } -func ConvertLogFromProto(p *Log) (*typesolana.Log, error) { +func ConvertLogFromProto(p *Log) (*solana.Log, error) { if p == nil { return nil, nil } @@ -1310,7 +1309,7 @@ func ConvertLogFromProto(p *Log) (*typesolana.Log, error) { lErr = &p.Error } - return &typesolana.Log{ + return &solana.Log{ ChainID: p.ChainId, LogIndex: p.LogIndex, BlockHash: bh, @@ -1325,7 +1324,7 @@ func ConvertLogFromProto(p *Log) (*typesolana.Log, error) { }, nil } -func ConvertLogToProto(l *typesolana.Log) *Log { +func ConvertLogToProto(l *solana.Log) *Log { if l == nil { return nil } @@ -1520,11 +1519,11 @@ func convertSolPrimitiveFromProto(protoPrimitive *Primitive) (query.Expression, } } -func ConvertLPFilterQueryFromProto(p *LPFilterQuery) (*typesolana.LPFilterQuery, error) { +func ConvertLPFilterQueryFromProto(p *LPFilterQuery) (*solana.LPFilterQuery, error) { if p == nil { return nil, nil } - var addr typesolana.PublicKey + var addr solana.PublicKey var err error if len(p.Address) > 0 { addr, err = ConvertPublicKeyFromProto(p.Address) @@ -1533,7 +1532,7 @@ func ConvertLPFilterQueryFromProto(p *LPFilterQuery) (*typesolana.LPFilterQuery, } } var err2 error - var eventSig typesolana.EventSignature + var eventSig solana.EventSignature if len(p.EventSig) > 0 { eventSig, err2 = ConvertEventSigFromProto(p.EventSig) if err != nil { @@ -1541,7 +1540,7 @@ func ConvertLPFilterQueryFromProto(p *LPFilterQuery) (*typesolana.LPFilterQuery, } } - return &typesolana.LPFilterQuery{ + return &solana.LPFilterQuery{ Name: p.Name, Address: addr, EventName: p.EventName, @@ -1581,7 +1580,7 @@ func ConvertSubkeyPathsToProto(keys [][]string) []*Subkeys { return out } -func ConvertLPFilterQueryToProto(f *typesolana.LPFilterQuery) *LPFilterQuery { +func ConvertLPFilterQueryToProto(f *solana.LPFilterQuery) *LPFilterQuery { if f == nil { return nil } @@ -1611,5 +1610,5 @@ func ptrUint64(v uint64) *uint64 { return &v } -func ptrBool(v bool) *bool { return &v } -func ptrUnix(v typesolana.UnixTimeSeconds) *typesolana.UnixTimeSeconds { return &v } + +func ptrUnix(v solana.UnixTimeSeconds) *solana.UnixTimeSeconds { return &v } diff --git a/pkg/codec/byte_string_modifier.go b/pkg/codec/byte_string_modifier.go index a0e69535ef..0796c03535 100644 --- a/pkg/codec/byte_string_modifier.go +++ b/pkg/codec/byte_string_modifier.go @@ -169,7 +169,7 @@ func (m *bytesToStringModifier) RetypeToOffChain(onChainType reflect.Type, _ str // TransformToOnChain uses the AddressModifier for string-to-address conversion. func (m *bytesToStringModifier) TransformToOnChain(offChainValue any, itemType string) (any, error) { - offChainValue, itemType, err := m.modifierBase.selectType(offChainValue, m.offChainStructType, itemType) + offChainValue, itemType, err := m.selectType(offChainValue, m.offChainStructType, itemType) if err != nil { return nil, err } @@ -188,7 +188,7 @@ func (m *bytesToStringModifier) TransformToOnChain(offChainValue any, itemType s // TransformToOffChain uses the AddressModifier for address-to-string conversion. func (m *bytesToStringModifier) TransformToOffChain(onChainValue any, itemType string) (any, error) { - onChainValue, itemType, err := m.modifierBase.selectType(onChainValue, m.onChainStructType, itemType) + onChainValue, itemType, err := m.selectType(onChainValue, m.onChainStructType, itemType) if err != nil { return nil, err } diff --git a/pkg/codec/epoch_to_time.go b/pkg/codec/epoch_to_time.go index 3f5795dc46..04214f05fe 100644 --- a/pkg/codec/epoch_to_time.go +++ b/pkg/codec/epoch_to_time.go @@ -46,7 +46,7 @@ type timeToUnixModifier struct { } func (m *timeToUnixModifier) TransformToOnChain(offChainValue any, itemType string) (any, error) { - offChainValue, itemType, err := m.modifierBase.selectType(offChainValue, m.offChainStructType, itemType) + offChainValue, itemType, err := m.selectType(offChainValue, m.offChainStructType, itemType) if err != nil { return nil, err } @@ -65,7 +65,7 @@ func (m *timeToUnixModifier) TransformToOnChain(offChainValue any, itemType stri } func (m *timeToUnixModifier) TransformToOffChain(onChainValue any, itemType string) (any, error) { - onChainValue, itemType, err := m.modifierBase.selectType(onChainValue, m.onChainStructType, itemType) + onChainValue, itemType, err := m.selectType(onChainValue, m.onChainStructType, itemType) if err != nil { return nil, err } diff --git a/pkg/codec/hard_coder.go b/pkg/codec/hard_coder.go index 44e6725227..e6a2164df0 100644 --- a/pkg/codec/hard_coder.go +++ b/pkg/codec/hard_coder.go @@ -103,7 +103,7 @@ func verifyHardCodeKeys(values map[string]any) error { // intended to be the result of the transformation, itemType must be A.B.C even though the off-chain type does not have // field 'C'. func (m *onChainHardCoder) TransformToOnChain(offChainValue any, itemType string) (any, error) { - offChainValue, itemType, err := m.modifierBase.selectType(offChainValue, m.offChainStructType, itemType) + offChainValue, itemType, err := m.selectType(offChainValue, m.offChainStructType, itemType) if err != nil { return nil, err } @@ -128,7 +128,7 @@ func (m *onChainHardCoder) TransformToOnChain(offChainValue any, itemType string // intended to be the result of the transformation, itemType must be A.B.C even though the on-chain type does not have // field 'C'. func (m *onChainHardCoder) TransformToOffChain(onChainValue any, itemType string) (any, error) { - onChainValue, itemType, err := m.modifierBase.selectType(onChainValue, m.onChainStructType, itemType) + onChainValue, itemType, err := m.selectType(onChainValue, m.onChainStructType, itemType) if err != nil { return nil, err } diff --git a/pkg/codec/precodec.go b/pkg/codec/precodec.go index 0285b335a4..3732f55d6a 100644 --- a/pkg/codec/precodec.go +++ b/pkg/codec/precodec.go @@ -72,7 +72,7 @@ type preCodec struct { func (pc *preCodec) TransformToOffChain(onChainValue any, itemType string) (any, error) { // set itemType to an ignore value if path traversal is not enabled - if !pc.modifierBase.enablePathTraverse { + if !pc.enablePathTraverse { itemType = "" } @@ -139,7 +139,7 @@ func (pc *preCodec) TransformToOnChain(offChainValue any, itemType string) (any, allHooks[0] = hardCodeManyHook // set itemType to an ignore value if path traversal is not enabled - if !pc.modifierBase.enablePathTraverse { + if !pc.enablePathTraverse { itemType = "" } diff --git a/pkg/codec/property_extractor.go b/pkg/codec/property_extractor.go index 7a1c12e4a2..e3551d993c 100644 --- a/pkg/codec/property_extractor.go +++ b/pkg/codec/property_extractor.go @@ -470,7 +470,7 @@ type NoSliceUnderFieldPathError struct { } func (e *NoSliceUnderFieldPathError) Error() string { - return fmt.Sprintf("field path did not resolve to a slice") + return "field path did not resolve to a slice" } func initSliceForFieldPath(rootType reflect.Type, fieldPath string) (reflect.Value, error) { diff --git a/pkg/codec/renamer.go b/pkg/codec/renamer.go index fed6b3f534..8aa9ee17dc 100644 --- a/pkg/codec/renamer.go +++ b/pkg/codec/renamer.go @@ -38,7 +38,7 @@ type renamer struct { func (r *renamer) TransformToOffChain(onChainValue any, itemType string) (any, error) { // set itemType to an ignore value if path traversal is not enabled - if !r.modifierBase.enablePathTraverse { + if !r.enablePathTraverse { itemType = "" } @@ -73,7 +73,7 @@ func (r *renamer) TransformToOffChain(onChainValue any, itemType string) (any, e func (r *renamer) TransformToOnChain(offChainValue any, itemType string) (any, error) { // set itemType to an ignore value if path traversal is not enabled - if !r.modifierBase.enablePathTraverse { + if !r.enablePathTraverse { itemType = "" } diff --git a/pkg/codec/utils.go b/pkg/codec/utils.go index 0446bd6d11..938d588ef9 100644 --- a/pkg/codec/utils.go +++ b/pkg/codec/utils.go @@ -242,9 +242,10 @@ func EpochToTimeHook(from reflect.Type, to reflect.Type, data any) (any, error) return convertToEpoch(to, time.Unix(unixTime, 0)), nil default: // value to time.Time - if to == timeType { + switch to { + case timeType: return convertToTime(from, data), nil - } else if to == timePtrType { + case timePtrType: if t, ok := convertToTime(from, data).(time.Time); ok { return &t, nil } diff --git a/pkg/codec/wrapper.go b/pkg/codec/wrapper.go index 597c8a0bce..564426aa98 100644 --- a/pkg/codec/wrapper.go +++ b/pkg/codec/wrapper.go @@ -66,7 +66,7 @@ func (m *wrapperModifier) RetypeToOffChain(onChainType reflect.Type, _ string) ( } func (m *wrapperModifier) TransformToOnChain(offChainValue any, itemType string) (any, error) { - offChainValue, itemType, err := m.modifierBase.selectType(offChainValue, m.offChainStructType, itemType) + offChainValue, itemType, err := m.selectType(offChainValue, m.offChainStructType, itemType) if err != nil { return nil, err } @@ -93,7 +93,7 @@ func (m *wrapperModifier) TransformToOnChain(offChainValue any, itemType string) } func (m *wrapperModifier) TransformToOffChain(onChainValue any, itemType string) (any, error) { - onChainValue, itemType, err := m.modifierBase.selectType(onChainValue, m.onChainStructType, itemType) + onChainValue, itemType, err := m.selectType(onChainValue, m.onChainStructType, itemType) if err != nil { return nil, err } diff --git a/pkg/config/secret_test.go b/pkg/config/secret_test.go index 279633a4d5..9aa6a7a274 100644 --- a/pkg/config/secret_test.go +++ b/pkg/config/secret_test.go @@ -25,7 +25,7 @@ func TestSecrets_redacted(t *testing.T) { assert.Equal(t, redacted, string(got)) } assert.Equal(t, redacted, fmt.Sprint(v)) - assert.Equal(t, redacted, fmt.Sprintf("%s", v)) //nolint:gosimple + assert.Equal(t, redacted, v.String()) //nolint:gosimple assert.Equal(t, redacted, fmt.Sprintf("%v", v)) assert.Equal(t, redacted, fmt.Sprintf("%#v", v)) got, err = json.Marshal(v) diff --git a/pkg/http/http.go b/pkg/http/http.go index e12a8cc1cb..163446dc83 100644 --- a/pkg/http/http.go +++ b/pkg/http/http.go @@ -84,7 +84,7 @@ func (h *Request) SendRequestReader() (responseBody io.ReadCloser, statusCode in elapsed := time.Since(start) logger.Sugared(h.Logger).Tracew(fmt.Sprintf("http adapter got %v in %s", statusCode, elapsed), "statusCode", statusCode, "timeElapsedSeconds", elapsed) - var source io.ReadCloser = r.Body + var source = r.Body if h.Config.SizeLimit > 0 { source = http.MaxBytesReader(&noOpResponseWriter{}, r.Body, h.Config.SizeLimit) } diff --git a/pkg/jsonrpc2/utils_test.go b/pkg/jsonrpc2/utils_test.go index 83c0e01eee..cce1ee57ca 100644 --- a/pkg/jsonrpc2/utils_test.go +++ b/pkg/jsonrpc2/utils_test.go @@ -13,7 +13,7 @@ const ( ) func TestHandler_DecodeRequest(t *testing.T) { - var paramsStr string = "params" + var paramsStr = "params" rawParams, err := json.Marshal(paramsStr) if err != nil { t.Fatalf("unexpected error: %v", err) @@ -117,7 +117,7 @@ func TestHandler_DecodeRequest(t *testing.T) { func TestHandler_EncodeRequest(t *testing.T) { t.Run("json.RawMessage", func(t *testing.T) { - var paramsStr string = "params" + var paramsStr = "params" rawParams, err := json.Marshal(paramsStr) if err != nil { t.Fatalf("unexpected error: %v", err) diff --git a/pkg/logger/logger.go b/pkg/logger/logger.go index 90c6e79c0b..1906bffd31 100644 --- a/pkg/logger/logger.go +++ b/pkg/logger/logger.go @@ -170,12 +170,12 @@ type logger struct { } func (l *logger) with(args ...any) Logger { - return &logger{l.SugaredLogger.With(args...)} + return &logger{l.With(args...)} } func (l *logger) named(name string) Logger { newLogger := *l - newLogger.SugaredLogger = l.SugaredLogger.Named(name) + newLogger.SugaredLogger = l.Named(name) return &newLogger } @@ -192,7 +192,7 @@ func (l *logger) sugaredHelper(skip int) *zap.SugaredLogger { } func (l *logger) withOptions(opts ...zap.Option) *zap.SugaredLogger { - return l.SugaredLogger.WithOptions(opts...) + return l.WithOptions(opts...) } // With returns a Logger with keyvals, if 'l' has a method `With(...any) L`, where L implements Logger, otherwise it returns l. diff --git a/pkg/logger/logger_test.go b/pkg/logger/logger_test.go index 02797637eb..eb0fdeaf92 100644 --- a/pkg/logger/logger_test.go +++ b/pkg/logger/logger_test.go @@ -236,7 +236,7 @@ func (o *other) With(args ...any) Logger { } func (o *other) Helper(skip int) Logger { - return &other{o.SugaredLogger.WithOptions(zap.AddCallerSkip(skip))} + return &other{o.WithOptions(zap.AddCallerSkip(skip))} } func (o *other) Name() string { @@ -268,7 +268,7 @@ func (d *different) With(args ...any) differentLogger { } func (d *different) Helper(skip int) differentLogger { - return &different{d.SugaredLogger.WithOptions(zap.AddCallerSkip(skip))} + return &different{d.WithOptions(zap.AddCallerSkip(skip))} } func (d *different) Name() string { @@ -290,7 +290,7 @@ func (m *mismatch) With(args ...any) any { } func (m *mismatch) Helper(skip int) any { - return &mismatch{m.SugaredLogger.WithOptions(zap.AddCallerSkip(skip))} + return &mismatch{m.WithOptions(zap.AddCallerSkip(skip))} } func (m *mismatch) Name() string { diff --git a/pkg/logger/otelzap/otelzap_test.go b/pkg/logger/otelzap/otelzap_test.go index 08fc963990..44e04bf1a4 100644 --- a/pkg/logger/otelzap/otelzap_test.go +++ b/pkg/logger/otelzap/otelzap_test.go @@ -23,12 +23,6 @@ type stringerMock struct{} func (s stringerMock) String() string { return "stringer-value" } -type customError struct{} - -func (e *customError) Error() string { - return "custom error" -} - // panicError will panic if Error() is called on a nil receiver type panicError struct { msg string diff --git a/pkg/loop/ccip_commit_test.go b/pkg/loop/ccip_commit_test.go index 06281cd67c..252f969643 100644 --- a/pkg/loop/ccip_commit_test.go +++ b/pkg/loop/ccip_commit_test.go @@ -34,7 +34,7 @@ func TestCommitService(t *testing.T) { require.NotPanics(t, func() { commit.Name() }) }) - hook := commit.PluginService.XXXTestHook() + hook := commit.XXXTestHook() servicetest.Run(t, commit) t.Run("control", func(t *testing.T) { diff --git a/pkg/loop/ccip_execution_test.go b/pkg/loop/ccip_execution_test.go index b665e156e4..0634522162 100644 --- a/pkg/loop/ccip_execution_test.go +++ b/pkg/loop/ccip_execution_test.go @@ -29,7 +29,7 @@ func TestExecService(t *testing.T) { exec := loop.NewExecutionService(logger.Test(t), loop.GRPCOpts{}, func() *exec.Cmd { return NewHelperProcessCommand(loop.CCIPExecutionLOOPName, false, 0) }, cciptest.ExecutionProvider(lggr), cciptest.ExecutionProvider(lggr), 0, 0, "") - hook := exec.PluginService.XXXTestHook() + hook := exec.XXXTestHook() servicetest.Run(t, exec) t.Run("control", func(t *testing.T) { diff --git a/pkg/loop/cmd/loopinstall/main_test.go b/pkg/loop/cmd/loopinstall/main_test.go index 5740b06036..2dddb3f64c 100644 --- a/pkg/loop/cmd/loopinstall/main_test.go +++ b/pkg/loop/cmd/loopinstall/main_test.go @@ -609,7 +609,7 @@ func TestDownloadAndInstallPlugin(t *testing.T) { mockDownload: func(cmd *exec.Cmd) error { if stdout, ok := cmd.Stdout.(*bytes.Buffer); ok { moduleDir := filepath.Join(tempDir, "modules", "github.com", "example", "test") - stdout.WriteString(fmt.Sprintf(`{"Dir":"%s"}`, moduleDir)) + fmt.Fprintf(stdout, `{"Dir":"%s"}`, moduleDir) } return nil }, @@ -646,7 +646,7 @@ func TestDownloadAndInstallPlugin(t *testing.T) { mockDownload: func(cmd *exec.Cmd) error { if stdout, ok := cmd.Stdout.(*bytes.Buffer); ok { moduleDir := filepath.Join(tempDir, "modules", "github.com", "example", "test") - stdout.WriteString(fmt.Sprintf(`{"Dir":"%s"}`, moduleDir)) + fmt.Fprintf(stdout, `{"Dir":"%s"}`, moduleDir) } return nil }, @@ -680,7 +680,7 @@ func TestDownloadAndInstallPlugin(t *testing.T) { // Derive moduleDir from ModuleURI for consistency parts := strings.Split("github.com/example/full", "/") moduleDir := filepath.Join(append([]string{tempDir, "modules"}, parts...)...) - stdout.WriteString(fmt.Sprintf(`{"Dir":"%s"}`, moduleDir)) + fmt.Fprintf(stdout, `{"Dir":"%s"}`, moduleDir) } return nil }, @@ -709,7 +709,7 @@ func TestDownloadAndInstallPlugin(t *testing.T) { if stdout, ok := cmd.Stdout.(*bytes.Buffer); ok { parts := strings.Split("github.com/example/rootinstall", "/") moduleDir := filepath.Join(append([]string{tempDir, "modules"}, parts...)...) - stdout.WriteString(fmt.Sprintf(`{"Dir":"%s"}`, moduleDir)) + fmt.Fprintf(stdout, `{"Dir":"%s"}`, moduleDir) } return nil }, @@ -793,7 +793,7 @@ func TestFlags(t *testing.T) { if stdout, ok := cmd.Stdout.(*bytes.Buffer); ok { parts := strings.Split("github.com/example/rootinstall", "/") moduleDir := filepath.Join(append([]string{tempDir, "modules"}, parts...)...) - stdout.WriteString(fmt.Sprintf(`{"Dir":"%s"}`, moduleDir)) + fmt.Fprintf(stdout, `{"Dir":"%s"}`, moduleDir) } return nil } @@ -868,7 +868,7 @@ func TestEnvVars(t *testing.T) { if stdout, ok := cmd.Stdout.(*bytes.Buffer); ok { parts := strings.Split("github.com/example/test", "/") moduleDir := filepath.Join(append([]string{tempDir, "modules"}, parts...)...) - stdout.WriteString(fmt.Sprintf(`{"Dir":"%s"}`, moduleDir)) + fmt.Fprintf(stdout, `{"Dir":"%s"}`, moduleDir) } return nil } @@ -951,7 +951,7 @@ func TestEnvVars(t *testing.T) { if stdout, ok := cmd.Stdout.(*bytes.Buffer); ok { parts := strings.Split("github.com/example/test", "/") moduleDir := filepath.Join(append([]string{tempDir, "modules"}, parts...)...) - stdout.WriteString(fmt.Sprintf(`{"Dir":"%s"}`, moduleDir)) + fmt.Fprintf(stdout, `{"Dir":"%s"}`, moduleDir) } return nil } @@ -992,15 +992,7 @@ func TestEnvVars(t *testing.T) { } // Set GOOS in the environment to a different value - oldGOOS := os.Getenv("GOOS") - os.Setenv("GOOS", "darwin") - defer func() { - if oldGOOS == "" { - os.Unsetenv("GOOS") - } else { - os.Setenv("GOOS", oldGOOS) - } - }() + t.Setenv("GOOS", "darwin") defaults := DefaultsConfig{ EnvVars: []string{"GOOS=linux"}, // Override with linux @@ -1037,7 +1029,7 @@ func TestEnvVars(t *testing.T) { if stdout, ok := cmd.Stdout.(*bytes.Buffer); ok { parts := strings.Split("github.com/example/test", "/") moduleDir := filepath.Join(append([]string{tempDir, "modules"}, parts...)...) - stdout.WriteString(fmt.Sprintf(`{"Dir":"%s"}`, moduleDir)) + fmt.Fprintf(stdout, `{"Dir":"%s"}`, moduleDir) } return nil } @@ -1085,15 +1077,7 @@ func TestEnvVars(t *testing.T) { } // Set CL_PLUGIN_ENVVARS - oldEnvVars := os.Getenv("CL_PLUGIN_ENVVARS") - os.Setenv("CL_PLUGIN_ENVVARS", "GOARCH=amd64 CGO_ENABLED=0") - defer func() { - if oldEnvVars == "" { - os.Unsetenv("CL_PLUGIN_ENVVARS") - } else { - os.Setenv("CL_PLUGIN_ENVVARS", oldEnvVars) - } - }() + t.Setenv("CL_PLUGIN_ENVVARS", "GOARCH=amd64 CGO_ENABLED=0") defaults := DefaultsConfig{ EnvVars: []string{"GOOS=linux"}, // Should be preserved @@ -1130,7 +1114,7 @@ func TestEnvVars(t *testing.T) { if stdout, ok := cmd.Stdout.(*bytes.Buffer); ok { parts := strings.Split("github.com/example/test", "/") moduleDir := filepath.Join(append([]string{tempDir, "modules"}, parts...)...) - stdout.WriteString(fmt.Sprintf(`{"Dir":"%s"}`, moduleDir)) + fmt.Fprintf(stdout, `{"Dir":"%s"}`, moduleDir) } return nil } @@ -1171,15 +1155,7 @@ func TestEnvVars(t *testing.T) { } // Set CL_PLUGIN_ENVVARS with a different GOOS - oldEnvVars := os.Getenv("CL_PLUGIN_ENVVARS") - os.Setenv("CL_PLUGIN_ENVVARS", "GOOS=linux") - defer func() { - if oldEnvVars == "" { - os.Unsetenv("CL_PLUGIN_ENVVARS") - } else { - os.Setenv("CL_PLUGIN_ENVVARS", oldEnvVars) - } - }() + t.Setenv("CL_PLUGIN_ENVVARS", "GOOS=linux") defaults := DefaultsConfig{ EnvVars: []string{"GOOS=darwin"}, // Should be overridden diff --git a/pkg/loop/config_test.go b/pkg/loop/config_test.go index a0b5ef83d9..9a0b6daf23 100644 --- a/pkg/loop/config_test.go +++ b/pkg/loop/config_test.go @@ -1,7 +1,6 @@ package loop import ( - "os" "strconv" "strings" "testing" @@ -245,15 +244,9 @@ func TestEnvConfig_AsCmdEnv(t *testing.T) { } func TestGetMap(t *testing.T) { - os.Setenv("TEST_PREFIX_KEY1", "value1") - os.Setenv("TEST_PREFIX_KEY2", "value2") - os.Setenv("OTHER_KEY", "othervalue") - - defer func() { - os.Unsetenv("TEST_PREFIX_KEY1") - os.Unsetenv("TEST_PREFIX_KEY2") - os.Unsetenv("OTHER_KEY") - }() + t.Setenv("TEST_PREFIX_KEY1", "value1") + t.Setenv("TEST_PREFIX_KEY2", "value2") + t.Setenv("OTHER_KEY", "othervalue") result := getMap("TEST_PREFIX_") @@ -292,7 +285,7 @@ func TestManagedGRPCClientConfig(t *testing.T) { assert.NotNil(t, clientConfig.Logger) assert.Equal(t, []plugin.Protocol{plugin.ProtocolGRPC}, clientConfig.AllowedProtocols) - assert.Equal(t, brokerConfig.GRPCOpts.DialOpts, clientConfig.GRPCDialOptions) + assert.Equal(t, brokerConfig.DialOpts, clientConfig.GRPCDialOptions) assert.True(t, clientConfig.Managed) }) } diff --git a/pkg/loop/internal/core/services/reportingplugin/ocr2/reporting.go b/pkg/loop/internal/core/services/reportingplugin/ocr2/reporting.go index f3969d7640..1387088d11 100644 --- a/pkg/loop/internal/core/services/reportingplugin/ocr2/reporting.go +++ b/pkg/loop/internal/core/services/reportingplugin/ocr2/reporting.go @@ -57,7 +57,7 @@ func (r *ReportingPluginFactoryClient) NewReportingPlugin(ctx context.Context, c MaxReportLength: int(reply.ReportingPluginInfo.ReportingPluginLimits.MaxReportLength), }, } - cc, err := r.BrokerExt.Dial(reply.ReportingPluginID) + cc, err := r.Dial(reply.ReportingPluginID) if err != nil { return nil, libocr.ReportingPluginInfo{}, err } diff --git a/pkg/loop/internal/core/services/reportingplugin/ocr2/reporting_plugin_service.go b/pkg/loop/internal/core/services/reportingplugin/ocr2/reporting_plugin_service.go index 2621ba778c..9f3a0c663c 100644 --- a/pkg/loop/internal/core/services/reportingplugin/ocr2/reporting_plugin_service.go +++ b/pkg/loop/internal/core/services/reportingplugin/ocr2/reporting_plugin_service.go @@ -125,7 +125,7 @@ func (m *ReportingPluginServiceClient) NewReportingPluginFactory( } return reply.ID, nil, nil }) - return NewReportingPluginFactoryClient(m.PluginClient.BrokerExt, cc), nil + return NewReportingPluginFactoryClient(m.BrokerExt, cc), nil } func (m *ReportingPluginServiceClient) NewValidationService(ctx context.Context) (core.ValidationService, error) { @@ -136,7 +136,7 @@ func (m *ReportingPluginServiceClient) NewValidationService(ctx context.Context) } return reply.ID, nil, nil }) - return validation.NewValidationServiceClient(m.PluginClient.BrokerExt, cc), nil + return validation.NewValidationServiceClient(m.BrokerExt, cc), nil } var _ pb.ReportingPluginServiceServer = (*reportingPluginServiceServer)(nil) diff --git a/pkg/loop/internal/core/services/reportingplugin/ocr3/reporting.go b/pkg/loop/internal/core/services/reportingplugin/ocr3/reporting.go index 702c069620..ad345e5dda 100644 --- a/pkg/loop/internal/core/services/reportingplugin/ocr3/reporting.go +++ b/pkg/loop/internal/core/services/reportingplugin/ocr3/reporting.go @@ -56,7 +56,7 @@ func (r *reportingPluginFactoryClient) NewReportingPlugin(ctx context.Context, c MaxReportCount: int(reply.ReportingPluginInfo.ReportingPluginLimits.MaxReportCount), }, } - cc, err := r.BrokerExt.Dial(reply.ReportingPluginID) + cc, err := r.Dial(reply.ReportingPluginID) if err != nil { return nil, ocr3types.ReportingPluginInfo{}, err } diff --git a/pkg/loop/internal/core/services/reportingplugin/ocr3/reporting_plugin_service.go b/pkg/loop/internal/core/services/reportingplugin/ocr3/reporting_plugin_service.go index 185e1a0681..041ca67f65 100644 --- a/pkg/loop/internal/core/services/reportingplugin/ocr3/reporting_plugin_service.go +++ b/pkg/loop/internal/core/services/reportingplugin/ocr3/reporting_plugin_service.go @@ -129,7 +129,7 @@ func (o *ReportingPluginServiceClient) NewReportingPluginFactory( } return reply.ID, nil, nil }) - return NewReportingPluginFactoryClient(o.PluginClient.BrokerExt, cc), nil + return NewReportingPluginFactoryClient(o.BrokerExt, cc), nil } func (o *ReportingPluginServiceClient) NewValidationService(ctx context.Context) (core.ValidationService, error) { @@ -140,7 +140,7 @@ func (o *ReportingPluginServiceClient) NewValidationService(ctx context.Context) } return reply.ID, nil, nil }) - return validation.NewValidationServiceClient(o.PluginClient.BrokerExt, cc), nil + return validation.NewValidationServiceClient(o.BrokerExt, cc), nil } var _ pb.ReportingPluginServiceServer = (*reportingPluginServiceServer)(nil) diff --git a/pkg/loop/internal/core/services/telemetry/test/telemetry.go b/pkg/loop/internal/core/services/telemetry/test/telemetry.go index ca4a9ef031..1ae90732af 100644 --- a/pkg/loop/internal/core/services/telemetry/test/telemetry.go +++ b/pkg/loop/internal/core/services/telemetry/test/telemetry.go @@ -41,7 +41,7 @@ type staticEndpoint struct { } func (s staticEndpoint) SendLog(ctx context.Context, log []byte) error { - return s.staticTelemetry.Send(ctx, s.network, s.chainID, s.contractID, s.telemType, log) + return s.Send(ctx, s.network, s.chainID, s.contractID, s.telemType, log) } type staticTelemetry struct { 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 697d74a44d..26c717c32c 100644 --- a/pkg/loop/internal/relayer/pluginprovider/contractreader/contract_reader_test.go +++ b/pkg/loop/internal/relayer/pluginprovider/contractreader/contract_reader_test.go @@ -357,15 +357,6 @@ type valConfidencePair struct { confidenceLevel primitives.ConfidenceLevel } -type eventConfidencePair struct { - testStruct TestStruct - confidenceLevel primitives.ConfidenceLevel -} - -type dynamicTopicEventConfidencePair struct { - someDynamicTopicEvent SomeDynamicTopicEvent - confidenceLevel primitives.ConfidenceLevel -} type event struct { contractID string event any @@ -676,17 +667,18 @@ func (f *fakeContractReader) BatchGetLatestValues(_ context.Context, request typ req := requestContractBatch[i] - if req.ReadName == MethodReturningUint64 { + switch req.ReadName { + case MethodReturningUint64: returnVal = req.ReturnVal.(*uint64) if requestContract.Name == AnyContractName { *returnVal.(*uint64) = AnyValueToReadWithoutAnArgument } else { *returnVal.(*uint64) = AnyDifferentValueToReadWithoutAnArgument } - } else if req.ReadName == MethodReturningUint64Slice { + case MethodReturningUint64Slice: returnVal = req.ReturnVal.(*[]uint64) *returnVal.(*[]uint64) = AnySliceToReadWithoutAnArgument - } else if req.ReadName == MethodReturningSeenStruct { + case MethodReturningSeenStruct: ts := *req.Params.(*TestStruct) ts.AccountStruct = AccountStruct{ Account: anyAccountBytes, @@ -697,7 +689,7 @@ func (f *fakeContractReader) BatchGetLatestValues(_ context.Context, request typ TestStruct: ts, ExtraField: AnyExtraValue, } - } else if req.ReadName == MethodTakingLatestParamsReturningTestStruct { + case MethodTakingLatestParamsReturningTestStruct: latestParams := requestContractBatch[i].Params.(*LatestParams) if latestParams.I <= 0 { returnVal = &LatestParams{} @@ -705,7 +697,7 @@ func (f *fakeContractReader) BatchGetLatestValues(_ context.Context, request typ } else { returnVal = storedContractBatch[latestParams.I-1].ReturnValue } - } else { + default: return nil, errors.New("unknown read " + req.ReadName) } diff --git a/pkg/loop/internal/relayer/pluginprovider/ext/ccip/commit_provider.go b/pkg/loop/internal/relayer/pluginprovider/ext/ccip/commit_provider.go index 4f9cd5294a..0df1862b09 100644 --- a/pkg/loop/internal/relayer/pluginprovider/ext/ccip/commit_provider.go +++ b/pkg/loop/internal/relayer/pluginprovider/ext/ccip/commit_provider.go @@ -13,7 +13,6 @@ import ( "github.com/smartcontractkit/chainlink-common/pkg/loop/internal/relayer/pluginprovider/ocr2" "github.com/smartcontractkit/chainlink-common/pkg/types" "github.com/smartcontractkit/chainlink-common/pkg/types/ccip" - cciptypes "github.com/smartcontractkit/chainlink-common/pkg/types/ccip" ) func RegisterCommitProviderServices(s *grpc.Server, provider types.CCIPCommitProvider, brokerExt *net.BrokerExt) { @@ -46,7 +45,7 @@ func NewCommitProviderClient(b *net.BrokerExt, conn grpc.ClientConnInterface) *C } // NewCommitStoreReader implements types.CCIPCommitProvider. -func (e *CommitProviderClient) NewCommitStoreReader(ctx context.Context, addr cciptypes.Address) (cciptypes.CommitStoreReader, error) { +func (e *CommitProviderClient) NewCommitStoreReader(ctx context.Context, addr ccip.Address) (ccip.CommitStoreReader, error) { req := ccippb.NewCommitStoreReaderRequest{Address: string(addr)} resp, err := e.grpcClient.NewCommitStoreReader(ctx, &req) @@ -54,7 +53,7 @@ func (e *CommitProviderClient) NewCommitStoreReader(ctx context.Context, addr cc return nil, err } // TODO BCF-3061: this works because the broker is shared and the id refers to a resource served by the broker - commitStoreConn, err := e.BrokerExt.Dial(uint32(resp.CommitStoreReaderServiceId)) + commitStoreConn, err := e.Dial(uint32(resp.CommitStoreReaderServiceId)) if err != nil { return nil, fmt.Errorf("failed to lookup off ramp reader service at %d: %w", resp.CommitStoreReaderServiceId, err) } @@ -63,7 +62,7 @@ func (e *CommitProviderClient) NewCommitStoreReader(ctx context.Context, addr cc } // NewOffRampReader implements types.CCIPCommitProvider. -func (e *CommitProviderClient) NewOffRampReader(ctx context.Context, addr cciptypes.Address) (cciptypes.OffRampReader, error) { +func (e *CommitProviderClient) NewOffRampReader(ctx context.Context, addr ccip.Address) (ccip.OffRampReader, error) { req := ccippb.NewOffRampReaderRequest{Address: string(addr)} resp, err := e.grpcClient.NewOffRampReader(ctx, &req) @@ -71,7 +70,7 @@ func (e *CommitProviderClient) NewOffRampReader(ctx context.Context, addr ccipty return nil, err } // TODO BCF-3061: this works because the broker is shared and the id refers to a resource served by the broker - offRampConn, err := e.BrokerExt.Dial(uint32(resp.OfframpReaderServiceId)) + offRampConn, err := e.Dial(uint32(resp.OfframpReaderServiceId)) if err != nil { return nil, fmt.Errorf("failed to lookup off ramp reader service at %d: %w", resp.OfframpReaderServiceId, err) } @@ -80,7 +79,7 @@ func (e *CommitProviderClient) NewOffRampReader(ctx context.Context, addr ccipty } // NewOnRampReader implements types.CCIPCommitProvider. -func (e *CommitProviderClient) NewOnRampReader(ctx context.Context, addr cciptypes.Address, sourceChainSelector uint64, destChainSelector uint64) (cciptypes.OnRampReader, error) { +func (e *CommitProviderClient) NewOnRampReader(ctx context.Context, addr ccip.Address, sourceChainSelector uint64, destChainSelector uint64) (ccip.OnRampReader, error) { req := ccippb.NewOnRampReaderRequest{Address: string(addr), SourceChainSelector: sourceChainSelector, DestChainSelector: destChainSelector} resp, err := e.grpcClient.NewOnRampReader(ctx, &req) @@ -92,7 +91,7 @@ func (e *CommitProviderClient) NewOnRampReader(ctx context.Context, addr cciptyp // because the broker is shared between the core node and relayer // this effectively let us proxy connects to resources spawn by the embedded relay // by hijacking the shared broker. id refers to a resource served by the shared broker - onRampConn, err := e.BrokerExt.Dial(uint32(resp.OnrampReaderServiceId)) + onRampConn, err := e.Dial(uint32(resp.OnrampReaderServiceId)) if err != nil { return nil, fmt.Errorf("failed to lookup on ramp reader service at %d: %w", resp.OnrampReaderServiceId, err) } @@ -101,13 +100,13 @@ func (e *CommitProviderClient) NewOnRampReader(ctx context.Context, addr cciptyp } // NewPriceGetter implements types.CCIPCommitProvider. -func (e *CommitProviderClient) NewPriceGetter(ctx context.Context) (cciptypes.PriceGetter, error) { +func (e *CommitProviderClient) NewPriceGetter(ctx context.Context) (ccip.PriceGetter, error) { resp, err := e.grpcClient.NewPriceGetter(ctx, &emptypb.Empty{}) if err != nil { return nil, err } // TODO BCF-3061: make this work for proxied relayer - priceGetterConn, err := e.BrokerExt.Dial(uint32(resp.PriceGetterServiceId)) + priceGetterConn, err := e.Dial(uint32(resp.PriceGetterServiceId)) if err != nil { return nil, fmt.Errorf("failed to lookup price getter service at %d: %w", resp.PriceGetterServiceId, err) } @@ -115,14 +114,14 @@ func (e *CommitProviderClient) NewPriceGetter(ctx context.Context) (cciptypes.Pr } // NewPriceRegistryReader implements types.CCIPCommitProvider. -func (e *CommitProviderClient) NewPriceRegistryReader(ctx context.Context, addr cciptypes.Address) (cciptypes.PriceRegistryReader, error) { +func (e *CommitProviderClient) NewPriceRegistryReader(ctx context.Context, addr ccip.Address) (ccip.PriceRegistryReader, error) { req := ccippb.NewPriceRegistryReaderRequest{Address: string(addr)} resp, err := e.grpcClient.NewPriceRegistryReader(ctx, &req) if err != nil { return nil, err } // TODO BCF-3061: make this work for proxied relayer - priceReaderConn, err := e.BrokerExt.Dial(uint32(resp.PriceRegistryReaderServiceId)) + priceReaderConn, err := e.Dial(uint32(resp.PriceRegistryReaderServiceId)) if err != nil { return nil, fmt.Errorf("failed to lookup price registry reader service at %d: %w", resp.PriceRegistryReaderServiceId, err) } @@ -131,7 +130,7 @@ func (e *CommitProviderClient) NewPriceRegistryReader(ctx context.Context, addr } // SourceNativeToken implements types.CCIPCommitProvider. -func (e *CommitProviderClient) SourceNativeToken(ctx context.Context, addr cciptypes.Address) (cciptypes.Address, error) { +func (e *CommitProviderClient) SourceNativeToken(ctx context.Context, addr ccip.Address) (ccip.Address, error) { // unlike the other methods, this one does not create a new resource, so we do not // need the broker to serve it. we can just call the grpc method directly. resp, err := e.grpcClient.SourceNativeToken(ctx, &ccippb.SourceNativeTokenRequest{ @@ -140,7 +139,7 @@ func (e *CommitProviderClient) SourceNativeToken(ctx context.Context, addr ccipt if err != nil { return "", err } - return cciptypes.Address(resp.NativeTokenAddress), nil + return ccip.Address(resp.NativeTokenAddress), nil } func (e *CommitProviderClient) Close() error { @@ -193,7 +192,7 @@ func NewCommitProviderServer(impl types.CCIPCommitProvider, brokerExt *net.Broke } func (e *CommitProviderServer) NewOffRampReader(ctx context.Context, req *ccippb.NewOffRampReaderRequest) (*ccippb.NewOffRampReaderResponse, error) { - reader, err := e.impl.NewOffRampReader(ctx, cciptypes.Address(req.Address)) + reader, err := e.impl.NewOffRampReader(ctx, ccip.Address(req.Address)) if err != nil { return nil, err } @@ -215,7 +214,7 @@ func (e *CommitProviderServer) NewOffRampReader(ctx context.Context, req *ccippb } func (e *CommitProviderServer) NewOnRampReader(ctx context.Context, req *ccippb.NewOnRampReaderRequest) (*ccippb.NewOnRampReaderResponse, error) { - reader, err := e.impl.NewOnRampReader(ctx, cciptypes.Address(req.Address), req.SourceChainSelector, req.DestChainSelector) + reader, err := e.impl.NewOnRampReader(ctx, ccip.Address(req.Address), req.SourceChainSelector, req.DestChainSelector) if err != nil { return nil, err } @@ -256,7 +255,7 @@ func (e *CommitProviderServer) NewPriceGetter(ctx context.Context, _ *emptypb.Em } func (e *CommitProviderServer) NewPriceRegistryReader(ctx context.Context, req *ccippb.NewPriceRegistryReaderRequest) (*ccippb.NewPriceRegistryReaderResponse, error) { - reader, err := e.impl.NewPriceRegistryReader(ctx, cciptypes.Address(req.Address)) + reader, err := e.impl.NewPriceRegistryReader(ctx, ccip.Address(req.Address)) if err != nil { return nil, err } @@ -278,7 +277,7 @@ func (e *CommitProviderServer) NewPriceRegistryReader(ctx context.Context, req * } func (e *CommitProviderServer) SourceNativeToken(ctx context.Context, req *ccippb.SourceNativeTokenRequest) (*ccippb.SourceNativeTokenResponse, error) { - addr, err := e.impl.SourceNativeToken(ctx, cciptypes.Address(req.SourceRouterAddress)) + addr, err := e.impl.SourceNativeToken(ctx, ccip.Address(req.SourceRouterAddress)) if err != nil { return nil, err } diff --git a/pkg/loop/internal/relayer/pluginprovider/ext/ccip/execution_provider.go b/pkg/loop/internal/relayer/pluginprovider/ext/ccip/execution_provider.go index 7e862c99c4..5a57705f5f 100644 --- a/pkg/loop/internal/relayer/pluginprovider/ext/ccip/execution_provider.go +++ b/pkg/loop/internal/relayer/pluginprovider/ext/ccip/execution_provider.go @@ -13,7 +13,6 @@ import ( "github.com/smartcontractkit/chainlink-common/pkg/loop/internal/relayer/pluginprovider/ocr2" "github.com/smartcontractkit/chainlink-common/pkg/types" "github.com/smartcontractkit/chainlink-common/pkg/types/ccip" - cciptypes "github.com/smartcontractkit/chainlink-common/pkg/types/ccip" ) func RegisterExecutionProviderServices(s *grpc.Server, provider types.CCIPExecProvider, brokerExt *net.BrokerExt) { @@ -57,7 +56,7 @@ func (e *ExecProviderClient) GetTransactionStatus(ctx context.Context, transacti } // NewCommitStoreReader implements types.CCIPExecProvider. -func (e *ExecProviderClient) NewCommitStoreReader(ctx context.Context, addr cciptypes.Address) (cciptypes.CommitStoreReader, error) { +func (e *ExecProviderClient) NewCommitStoreReader(ctx context.Context, addr ccip.Address) (ccip.CommitStoreReader, error) { req := ccippb.NewCommitStoreReaderRequest{Address: string(addr)} resp, err := e.grpcClient.NewCommitStoreReader(ctx, &req) @@ -65,7 +64,7 @@ func (e *ExecProviderClient) NewCommitStoreReader(ctx context.Context, addr ccip return nil, err } // TODO BCF-3061: this works because the broker is shared and the id refers to a resource served by the broker - commitStoreConn, err := e.BrokerExt.Dial(uint32(resp.CommitStoreReaderServiceId)) + commitStoreConn, err := e.Dial(uint32(resp.CommitStoreReaderServiceId)) if err != nil { return nil, fmt.Errorf("failed to lookup off ramp reader service at %d: %w", resp.CommitStoreReaderServiceId, err) } @@ -76,7 +75,7 @@ func (e *ExecProviderClient) NewCommitStoreReader(ctx context.Context, addr ccip } // NewOffRampReader implements types.CCIPExecProvider. -func (e *ExecProviderClient) NewOffRampReader(ctx context.Context, addr cciptypes.Address) (cciptypes.OffRampReader, error) { +func (e *ExecProviderClient) NewOffRampReader(ctx context.Context, addr ccip.Address) (ccip.OffRampReader, error) { req := ccippb.NewOffRampReaderRequest{Address: string(addr)} resp, err := e.grpcClient.NewOffRampReader(ctx, &req) @@ -84,7 +83,7 @@ func (e *ExecProviderClient) NewOffRampReader(ctx context.Context, addr cciptype return nil, err } // TODO BCF-3061: this works because the broker is shared and the id refers to a resource served by the broker - offRampConn, err := e.BrokerExt.Dial(uint32(resp.OfframpReaderServiceId)) + offRampConn, err := e.Dial(uint32(resp.OfframpReaderServiceId)) if err != nil { return nil, fmt.Errorf("failed to lookup off ramp reader service at %d: %w", resp.OfframpReaderServiceId, err) } @@ -95,7 +94,7 @@ func (e *ExecProviderClient) NewOffRampReader(ctx context.Context, addr cciptype } // NewOnRampReader implements types.CCIPExecProvider. -func (e *ExecProviderClient) NewOnRampReader(ctx context.Context, addr cciptypes.Address, srcChainSelector uint64, dstChainSelector uint64) (cciptypes.OnRampReader, error) { +func (e *ExecProviderClient) NewOnRampReader(ctx context.Context, addr ccip.Address, srcChainSelector uint64, dstChainSelector uint64) (ccip.OnRampReader, error) { req := ccippb.NewOnRampReaderRequest{Address: string(addr), SourceChainSelector: srcChainSelector, DestChainSelector: dstChainSelector} resp, err := e.grpcClient.NewOnRampReader(ctx, &req) @@ -107,26 +106,26 @@ func (e *ExecProviderClient) NewOnRampReader(ctx context.Context, addr cciptypes // because the broker is shared between the core node and relayer // this effectively let us proxy connects to resources spawn by the embedded relay // by hijacking the shared broker. id refers to a resource served by the shared broker - onRampConn, err := e.BrokerExt.Dial(uint32(resp.OnrampReaderServiceId)) + onRampConn, err := e.Dial(uint32(resp.OnrampReaderServiceId)) if err != nil { return nil, fmt.Errorf("failed to lookup on ramp reader service at %d: %w", resp.OnrampReaderServiceId, err) } // need to wrap grpc onRamp into the desired interface onRamp := NewOnRampReaderGRPCClient(onRampConn) - // how to convert resp to cciptypes.OnRampReader? i have an id and need to hydrate that into an instance of OnRampReader + // how to convert resp to ccip.OnRampReader? i have an id and need to hydrate that into an instance of OnRampReader return onRamp, nil } // NewPriceRegistryReader implements types.CCIPExecProvider. -func (e *ExecProviderClient) NewPriceRegistryReader(ctx context.Context, addr cciptypes.Address) (cciptypes.PriceRegistryReader, error) { +func (e *ExecProviderClient) NewPriceRegistryReader(ctx context.Context, addr ccip.Address) (ccip.PriceRegistryReader, error) { req := ccippb.NewPriceRegistryReaderRequest{Address: string(addr)} resp, err := e.grpcClient.NewPriceRegistryReader(ctx, &req) if err != nil { return nil, err } // TODO BCF-3061: make this work for proxied relayer - priceReaderConn, err := e.BrokerExt.Dial(uint32(resp.PriceRegistryReaderServiceId)) + priceReaderConn, err := e.Dial(uint32(resp.PriceRegistryReaderServiceId)) if err != nil { return nil, fmt.Errorf("failed to lookup price registry reader service at %d: %w", resp.PriceRegistryReaderServiceId, err) } @@ -137,14 +136,14 @@ func (e *ExecProviderClient) NewPriceRegistryReader(ctx context.Context, addr cc } // NewTokenDataReader implements types.CCIPExecProvider. -func (e *ExecProviderClient) NewTokenDataReader(ctx context.Context, tokenAddress cciptypes.Address) (cciptypes.TokenDataReader, error) { +func (e *ExecProviderClient) NewTokenDataReader(ctx context.Context, tokenAddress ccip.Address) (ccip.TokenDataReader, error) { req := ccippb.NewTokenDataRequest{Address: string(tokenAddress)} resp, err := e.grpcClient.NewTokenDataReader(ctx, &req) if err != nil { return nil, err } // TODO BCF-3061: make this work for proxied relayer - tokenDataConn, err := e.BrokerExt.Dial(uint32(resp.TokenDataReaderServiceId)) + tokenDataConn, err := e.Dial(uint32(resp.TokenDataReaderServiceId)) if err != nil { return nil, fmt.Errorf("failed to lookup token data reader service at %d: %w", resp.TokenDataReaderServiceId, err) } @@ -155,14 +154,14 @@ func (e *ExecProviderClient) NewTokenDataReader(ctx context.Context, tokenAddres } // NewTokenPoolBatchedReader implements types.CCIPExecProvider. -func (e *ExecProviderClient) NewTokenPoolBatchedReader(ctx context.Context, offRampAddress cciptypes.Address, srcChainSelector uint64) (cciptypes.TokenPoolBatchedReader, error) { +func (e *ExecProviderClient) NewTokenPoolBatchedReader(ctx context.Context, offRampAddress ccip.Address, srcChainSelector uint64) (ccip.TokenPoolBatchedReader, error) { req := ccippb.NewTokenPoolBatchedReaderRequest{Address: string(offRampAddress), SourceChainSelector: srcChainSelector} resp, err := e.grpcClient.NewTokenPoolBatchedReader(ctx, &req) if err != nil { return nil, err } // TODO BCF-3061: make this work for proxied relayer - tokenPoolConn, err := e.BrokerExt.Dial(uint32(resp.TokenPoolBatchedReaderServiceId)) + tokenPoolConn, err := e.Dial(uint32(resp.TokenPoolBatchedReaderServiceId)) if err != nil { return nil, fmt.Errorf("failed to lookup token poll batched reader service at %d: %w", resp.TokenPoolBatchedReaderServiceId, err) } @@ -171,14 +170,14 @@ func (e *ExecProviderClient) NewTokenPoolBatchedReader(ctx context.Context, offR } // SourceNativeToken implements types.CCIPExecProvider. -func (e *ExecProviderClient) SourceNativeToken(ctx context.Context, addr cciptypes.Address) (cciptypes.Address, error) { +func (e *ExecProviderClient) SourceNativeToken(ctx context.Context, addr ccip.Address) (ccip.Address, error) { // unlike the other methods, this one does not create a new resource, so we do not // need the broker to serve it. we can just call the grpc method directly. resp, err := e.grpcClient.SourceNativeToken(ctx, &ccippb.SourceNativeTokenRequest{SourceRouterAddress: string(addr)}) if err != nil { return "", err } - return cciptypes.Address(resp.NativeTokenAddress), nil + return ccip.Address(resp.NativeTokenAddress), nil } // Close implements types.CCIPExecProvider. @@ -239,7 +238,7 @@ func (e *ExecProviderServer) GetTransactionStatus(ctx context.Context, req *ccip } func (e *ExecProviderServer) NewOffRampReader(ctx context.Context, req *ccippb.NewOffRampReaderRequest) (*ccippb.NewOffRampReaderResponse, error) { - reader, err := e.impl.NewOffRampReader(ctx, cciptypes.Address(req.Address)) + reader, err := e.impl.NewOffRampReader(ctx, ccip.Address(req.Address)) if err != nil { return nil, err } @@ -261,7 +260,7 @@ func (e *ExecProviderServer) NewOffRampReader(ctx context.Context, req *ccippb.N } func (e *ExecProviderServer) NewOnRampReader(ctx context.Context, req *ccippb.NewOnRampReaderRequest) (*ccippb.NewOnRampReaderResponse, error) { - reader, err := e.impl.NewOnRampReader(ctx, cciptypes.Address(req.Address), req.SourceChainSelector, req.DestChainSelector) + reader, err := e.impl.NewOnRampReader(ctx, ccip.Address(req.Address), req.SourceChainSelector, req.DestChainSelector) if err != nil { return nil, err } @@ -280,7 +279,7 @@ func (e *ExecProviderServer) NewOnRampReader(ctx context.Context, req *ccippb.Ne } func (e *ExecProviderServer) NewPriceRegistryReader(ctx context.Context, req *ccippb.NewPriceRegistryReaderRequest) (*ccippb.NewPriceRegistryReaderResponse, error) { - reader, err := e.impl.NewPriceRegistryReader(ctx, cciptypes.Address(req.Address)) + reader, err := e.impl.NewPriceRegistryReader(ctx, ccip.Address(req.Address)) if err != nil { return nil, err } @@ -302,7 +301,7 @@ func (e *ExecProviderServer) NewPriceRegistryReader(ctx context.Context, req *cc } func (e *ExecProviderServer) NewTokenDataReader(ctx context.Context, req *ccippb.NewTokenDataRequest) (*ccippb.NewTokenDataResponse, error) { - reader, err := e.impl.NewTokenDataReader(ctx, cciptypes.Address(req.Address)) + reader, err := e.impl.NewTokenDataReader(ctx, ccip.Address(req.Address)) if err != nil { return nil, err } @@ -321,7 +320,7 @@ func (e *ExecProviderServer) NewTokenDataReader(ctx context.Context, req *ccippb } func (e *ExecProviderServer) NewTokenPoolBatchedReader(ctx context.Context, req *ccippb.NewTokenPoolBatchedReaderRequest) (*ccippb.NewTokenPoolBatchedReaderResponse, error) { - reader, err := e.impl.NewTokenPoolBatchedReader(ctx, cciptypes.Address(req.Address), req.SourceChainSelector) + reader, err := e.impl.NewTokenPoolBatchedReader(ctx, ccip.Address(req.Address), req.SourceChainSelector) if err != nil { return nil, err } @@ -340,7 +339,7 @@ func (e *ExecProviderServer) NewTokenPoolBatchedReader(ctx context.Context, req } func (e *ExecProviderServer) SourceNativeToken(ctx context.Context, req *ccippb.SourceNativeTokenRequest) (*ccippb.SourceNativeTokenResponse, error) { - addr, err := e.impl.SourceNativeToken(ctx, cciptypes.Address(req.SourceRouterAddress)) + addr, err := e.impl.SourceNativeToken(ctx, ccip.Address(req.SourceRouterAddress)) if err != nil { return nil, err } diff --git a/pkg/loop/internal/relayer/pluginprovider/ext/ccip/offramp.go b/pkg/loop/internal/relayer/pluginprovider/ext/ccip/offramp.go index e6f834bef8..486ee9763c 100644 --- a/pkg/loop/internal/relayer/pluginprovider/ext/ccip/offramp.go +++ b/pkg/loop/internal/relayer/pluginprovider/ext/ccip/offramp.go @@ -613,7 +613,7 @@ func executionStateChangedWithTxMetaToPB(in cciptypes.ExecutionStateChangedWithT return &ccippb.ExecutionStateChangeWithTxMeta{ TxMeta: txMetaToPB(in.TxMeta), ExecutionStateChange: &ccippb.ExecutionStateChange{ - SeqNum: in.ExecutionStateChanged.SequenceNumber, + SeqNum: in.SequenceNumber, }, } } diff --git a/pkg/loop/internal/relayer/pluginprovider/ext/ccip/pricegetter.go b/pkg/loop/internal/relayer/pluginprovider/ext/ccip/pricegetter.go index d933603b05..47c665178e 100644 --- a/pkg/loop/internal/relayer/pluginprovider/ext/ccip/pricegetter.go +++ b/pkg/loop/internal/relayer/pluginprovider/ext/ccip/pricegetter.go @@ -12,7 +12,6 @@ import ( ccippb "github.com/smartcontractkit/chainlink-common/pkg/loop/internal/pb/ccip" "github.com/smartcontractkit/chainlink-common/pkg/services" "github.com/smartcontractkit/chainlink-common/pkg/types/ccip" - cciptypes "github.com/smartcontractkit/chainlink-common/pkg/types/ccip" ) // PriceGetterGRPCClient implements [cciptypes.PriceGetter] by wrapping a @@ -35,16 +34,16 @@ func NewPriceGetterGRPCClient(cc grpc.ClientConnInterface) *PriceGetterGRPCClien type PriceGetterGRPCServer struct { ccippb.UnimplementedPriceGetterServer - impl cciptypes.PriceGetter + impl ccip.PriceGetter deps []io.Closer } -func NewPriceGetterGRPCServer(impl cciptypes.PriceGetter) *PriceGetterGRPCServer { +func NewPriceGetterGRPCServer(impl ccip.PriceGetter) *PriceGetterGRPCServer { return &PriceGetterGRPCServer{impl: impl, deps: []io.Closer{impl}} } // ensure the types are satisfied -var _ cciptypes.PriceGetter = (*PriceGetterGRPCClient)(nil) +var _ ccip.PriceGetter = (*PriceGetterGRPCClient)(nil) var _ ccippb.PriceGetterServer = (*PriceGetterGRPCServer)(nil) func (p *PriceGetterGRPCClient) ClientConn() grpc.ClientConnInterface { @@ -52,9 +51,9 @@ func (p *PriceGetterGRPCClient) ClientConn() grpc.ClientConnInterface { } // FilterConfiguredTokens implements ccip.PriceGetter. -func (p *PriceGetterGRPCClient) FilterConfiguredTokens(ctx context.Context, tokens []cciptypes.Address) (configured []cciptypes.Address, unconfigured []cciptypes.Address, err error) { - configured = []cciptypes.Address{} - unconfigured = []cciptypes.Address{} +func (p *PriceGetterGRPCClient) FilterConfiguredTokens(ctx context.Context, tokens []ccip.Address) (configured []ccip.Address, unconfigured []ccip.Address, err error) { + configured = []ccip.Address{} + unconfigured = []ccip.Address{} // convert the format requestedTokens := make([]string, len(tokens)) @@ -81,7 +80,7 @@ func (p *PriceGetterGRPCClient) FilterConfiguredTokens(ctx context.Context, toke } // TokenPricesUSD implements ccip.PriceGetter. -func (p *PriceGetterGRPCClient) TokenPricesUSD(ctx context.Context, tokens []cciptypes.Address) (map[cciptypes.Address]*big.Int, error) { +func (p *PriceGetterGRPCClient) TokenPricesUSD(ctx context.Context, tokens []ccip.Address) (map[ccip.Address]*big.Int, error) { // convert the format requestedTokens := make([]string, len(tokens)) for i, t := range tokens { @@ -92,7 +91,7 @@ func (p *PriceGetterGRPCClient) TokenPricesUSD(ctx context.Context, tokens []cci if err != nil { return nil, err } - prices := make(map[cciptypes.Address]*big.Int, len(resp.Prices)) + prices := make(map[ccip.Address]*big.Int, len(resp.Prices)) for addr, p := range resp.Prices { prices[ccip.Address(addr)] = p.Int() } @@ -105,9 +104,9 @@ func (p *PriceGetterGRPCClient) Close() error { // FilterConfiguredTokens implements ccippb.PriceGetterServer. func (p *PriceGetterGRPCServer) FilterConfiguredTokens(ctx context.Context, req *ccippb.FilterConfiguredTokensRequest) (*ccippb.FilterConfiguredTokensResponse, error) { - tokenAddresses := make([]cciptypes.Address, len(req.Tokens)) + tokenAddresses := make([]ccip.Address, len(req.Tokens)) for i, t := range req.Tokens { - tokenAddresses[i] = cciptypes.Address(t) + tokenAddresses[i] = ccip.Address(t) } configuredTokens, unconfiguredTokens, err := p.impl.FilterConfiguredTokens(ctx, tokenAddresses) @@ -129,9 +128,9 @@ func (p *PriceGetterGRPCServer) FilterConfiguredTokens(ctx context.Context, req // TokenPricesUSD implements ccippb.PriceGetterServer. func (p *PriceGetterGRPCServer) TokenPricesUSD(ctx context.Context, req *ccippb.TokenPricesRequest) (*ccippb.TokenPricesResponse, error) { - tokenAddresses := make([]cciptypes.Address, len(req.Tokens)) + tokenAddresses := make([]ccip.Address, len(req.Tokens)) for i, t := range req.Tokens { - tokenAddresses[i] = cciptypes.Address(t) + tokenAddresses[i] = ccip.Address(t) } prices, err := p.impl.TokenPricesUSD(ctx, tokenAddresses) diff --git a/pkg/loop/internal/relayer/pluginprovider/ext/ccip/test/commit_gas_estimator.go b/pkg/loop/internal/relayer/pluginprovider/ext/ccip/test/commit_gas_estimator.go index a1000c57fb..325bdd17c0 100644 --- a/pkg/loop/internal/relayer/pluginprovider/ext/ccip/test/commit_gas_estimator.go +++ b/pkg/loop/internal/relayer/pluginprovider/ext/ccip/test/commit_gas_estimator.go @@ -50,11 +50,11 @@ func (s staticGasPriceEstimatorCommit) DenoteInUSD(ctx context.Context, p *big.I // Deviates implements GasPriceEstimatorCommitEvaluator. func (s staticGasPriceEstimatorCommit) Deviates(ctx context.Context, p1 *big.Int, p2 *big.Int) (bool, error) { - if s.deviatesRequest.p1.Cmp(p1) != 0 { - return false, fmt.Errorf("expected p1 %v, got %v", s.deviatesRequest.p1, p1) + if s.p1.Cmp(p1) != 0 { + return false, fmt.Errorf("expected p1 %v, got %v", s.p1, p1) } - if s.deviatesRequest.p2.Cmp(p2) != 0 { - return false, fmt.Errorf("expected p2 %v, got %v", s.deviatesRequest.p2, p2) + if s.p2.Cmp(p2) != 0 { + return false, fmt.Errorf("expected p2 %v, got %v", s.p2, p2) } return s.deviatesResponse, nil } @@ -69,7 +69,7 @@ func (s staticGasPriceEstimatorCommit) Evaluate(ctx context.Context, other ccipt return fmt.Errorf("expected other.GetGasPrice %v, got %v", s.getGasPriceResponse, gotGas) } - gotMedian, err := other.Median(ctx, s.medianRequest.gasPrices) + gotMedian, err := other.Median(ctx, s.gasPrices) if err != nil { return fmt.Errorf("failed to other.Median: %w", err) } @@ -77,7 +77,7 @@ func (s staticGasPriceEstimatorCommit) Evaluate(ctx context.Context, other ccipt return fmt.Errorf("expected other.Median %v, got %v", s.medianResponse, gotMedian) } - gotDeviates, err := other.Deviates(ctx, s.deviatesRequest.p1, s.deviatesRequest.p2) + gotDeviates, err := other.Deviates(ctx, s.p1, s.p2) if err != nil { return fmt.Errorf("failed to other.Deviates: %w", err) } @@ -103,12 +103,12 @@ func (s staticGasPriceEstimatorCommit) GetGasPrice(ctx context.Context) (*big.In // Median implements GasPriceEstimatorCommitEvaluator. func (s staticGasPriceEstimatorCommit) Median(ctx context.Context, gasPrices []*big.Int) (*big.Int, error) { - if len(gasPrices) != len(s.medianRequest.gasPrices) { - return nil, fmt.Errorf("expected gas prices len %d, got %d", len(s.medianRequest.gasPrices), len(gasPrices)) + if len(gasPrices) != len(s.gasPrices) { + return nil, fmt.Errorf("expected gas prices len %d, got %d", len(s.gasPrices), len(gasPrices)) } for i, p := range gasPrices { if s.medianRequest.gasPrices[i].Cmp(p) != 0 { - return nil, fmt.Errorf("expected gas price %d %v, got %v", i, s.medianRequest.gasPrices[i], p) + return nil, fmt.Errorf("expected gas price %d %v, got %v", i, s.gasPrices[i], p) } } return s.medianResponse, nil diff --git a/pkg/loop/internal/relayer/pluginprovider/ext/ccip/test/commit_gas_estimator_test.go b/pkg/loop/internal/relayer/pluginprovider/ext/ccip/test/commit_gas_estimator_test.go index 9b15f4676e..a18498ec65 100644 --- a/pkg/loop/internal/relayer/pluginprovider/ext/ccip/test/commit_gas_estimator_test.go +++ b/pkg/loop/internal/relayer/pluginprovider/ext/ccip/test/commit_gas_estimator_test.go @@ -54,14 +54,14 @@ func roundTripGasPriceEstimatorCommitTests(t *testing.T, client *ccip.CommitGasE t.Run("Deviates", func(t *testing.T) { ctx := t.Context() - isDeviant, err := client.Deviates(ctx, GasPriceEstimatorCommit.deviatesRequest.p1, GasPriceEstimatorCommit.deviatesRequest.p2) + isDeviant, err := client.Deviates(ctx, GasPriceEstimatorCommit.p1, GasPriceEstimatorCommit.p2) require.NoError(t, err) assert.Equal(t, GasPriceEstimatorCommit.deviatesResponse, isDeviant) }) t.Run("Median", func(t *testing.T) { ctx := t.Context() - median, err := client.Median(ctx, GasPriceEstimatorCommit.medianRequest.gasPrices) + median, err := client.Median(ctx, GasPriceEstimatorCommit.gasPrices) require.NoError(t, err) assert.Equal(t, GasPriceEstimatorCommit.medianResponse, median) }) diff --git a/pkg/loop/internal/relayer/pluginprovider/ext/ccip/test/commit_store_test.go b/pkg/loop/internal/relayer/pluginprovider/ext/ccip/test/commit_store_test.go index af16cbc8d6..f7f6a7bf00 100644 --- a/pkg/loop/internal/relayer/pluginprovider/ext/ccip/test/commit_store_test.go +++ b/pkg/loop/internal/relayer/pluginprovider/ext/ccip/test/commit_store_test.go @@ -96,14 +96,14 @@ func roundTripCommitStoreTests(t *testing.T, client cciptypes.CommitStoreReader) t.Run("Deviates", func(t *testing.T) { ctx := t.Context() - deviates, err := estimator.Deviates(ctx, GasPriceEstimatorCommit.deviatesRequest.p1, GasPriceEstimatorCommit.deviatesRequest.p2) + deviates, err := estimator.Deviates(ctx, GasPriceEstimatorCommit.p1, GasPriceEstimatorCommit.p2) require.NoError(t, err) assert.Equal(t, GasPriceEstimatorCommit.deviatesResponse, deviates) }) t.Run("Median", func(t *testing.T) { ctx := t.Context() - median, err := estimator.Median(ctx, GasPriceEstimatorCommit.medianRequest.gasPrices) + median, err := estimator.Median(ctx, GasPriceEstimatorCommit.gasPrices) require.NoError(t, err) assert.Equal(t, GasPriceEstimatorCommit.medianResponse, median) }) diff --git a/pkg/loop/internal/relayer/pluginprovider/ext/ccip/test/exec_gas_estimator.go b/pkg/loop/internal/relayer/pluginprovider/ext/ccip/test/exec_gas_estimator.go index 453b30b31c..a2d89bd9ed 100644 --- a/pkg/loop/internal/relayer/pluginprovider/ext/ccip/test/exec_gas_estimator.go +++ b/pkg/loop/internal/relayer/pluginprovider/ext/ccip/test/exec_gas_estimator.go @@ -91,7 +91,7 @@ func (s staticGasPriceEstimatorExec) Evaluate(ctx context.Context, other cciptyp } // Median test case - gotMedian, err := other.Median(ctx, s.medianRequest.gasPrices) + gotMedian, err := other.Median(ctx, s.gasPrices) if err != nil { return fmt.Errorf("failed to other.Median: %w", err) } @@ -126,12 +126,12 @@ func (s staticGasPriceEstimatorExec) GetGasPrice(ctx context.Context) (*big.Int, // Median implements GasPriceEstimatorExecEvaluator. func (s staticGasPriceEstimatorExec) Median(ctx context.Context, gasPrices []*big.Int) (*big.Int, error) { - if len(gasPrices) != len(s.medianRequest.gasPrices) { - return nil, fmt.Errorf("expected gas prices len %d, got %d", len(s.medianRequest.gasPrices), len(gasPrices)) + if len(gasPrices) != len(s.gasPrices) { + return nil, fmt.Errorf("expected gas prices len %d, got %d", len(s.gasPrices), len(gasPrices)) } for i, p := range gasPrices { if s.medianRequest.gasPrices[i].Cmp(p) != 0 { - return nil, fmt.Errorf("expected gas price %d %v, got %v", i, s.medianRequest.gasPrices[i], p) + return nil, fmt.Errorf("expected gas price %d %v, got %v", i, s.gasPrices[i], p) } } return s.medianResponse, nil diff --git a/pkg/loop/internal/relayer/pluginprovider/ext/ccip/test/exec_gas_estimator_test.go b/pkg/loop/internal/relayer/pluginprovider/ext/ccip/test/exec_gas_estimator_test.go index 13b5175eb1..77e10650e2 100644 --- a/pkg/loop/internal/relayer/pluginprovider/ext/ccip/test/exec_gas_estimator_test.go +++ b/pkg/loop/internal/relayer/pluginprovider/ext/ccip/test/exec_gas_estimator_test.go @@ -61,7 +61,7 @@ func roundTripGasPriceEstimatorExecTests(t *testing.T, client *ccip.ExecGasEstim t.Run("Median", func(t *testing.T) { ctx := t.Context() - median, err := client.Median(ctx, GasPriceEstimatorExec.medianRequest.gasPrices) + median, err := client.Median(ctx, GasPriceEstimatorExec.gasPrices) require.NoError(t, err) assert.Equal(t, GasPriceEstimatorExec.medianResponse, median) }) diff --git a/pkg/loop/internal/relayer/pluginprovider/ext/ccip/test/offramp.go b/pkg/loop/internal/relayer/pluginprovider/ext/ccip/test/offramp.go index ff85e7af18..da6c1fae8e 100644 --- a/pkg/loop/internal/relayer/pluginprovider/ext/ccip/test/offramp.go +++ b/pkg/loop/internal/relayer/pluginprovider/ext/ccip/test/offramp.go @@ -391,7 +391,7 @@ func (s staticOffRamp) Evaluate(ctx context.Context, other ccip.OffRampReader) e return fmt.Errorf("expected cost %v but got %v", GasPriceEstimatorExec.estimateMsgCostUSDResponse, cost) } // Median test case - median, err := gasPriceEstimator.Median(ctx, GasPriceEstimatorExec.medianRequest.gasPrices) + median, err := gasPriceEstimator.Median(ctx, GasPriceEstimatorExec.gasPrices) if err != nil { return fmt.Errorf("failed to get other median: %w", err) } diff --git a/pkg/loop/internal/relayer/pluginprovider/ext/ccip/test/offramp_test.go b/pkg/loop/internal/relayer/pluginprovider/ext/ccip/test/offramp_test.go index 08cdef9262..704da1214e 100644 --- a/pkg/loop/internal/relayer/pluginprovider/ext/ccip/test/offramp_test.go +++ b/pkg/loop/internal/relayer/pluginprovider/ext/ccip/test/offramp_test.go @@ -59,10 +59,10 @@ func roundTripOffRampTests(t *testing.T, client cciptypes.OffRampReader) { }) t.Run("ChangeConfig", func(t *testing.T) { - gotAddr1, gotAddr2, err := client.ChangeConfig(t.Context(), OffRampReader.changeConfigRequest.onchainConfig, OffRampReader.changeConfigRequest.offchainConfig) + gotAddr1, gotAddr2, err := client.ChangeConfig(t.Context(), OffRampReader.onchainConfig, OffRampReader.offchainConfig) require.NoError(t, err) - assert.Equal(t, OffRampReader.changeConfigResponse.onchainConfigDigest, gotAddr1) - assert.Equal(t, OffRampReader.changeConfigResponse.offchainConfigDigest, gotAddr2) + assert.Equal(t, OffRampReader.onchainConfigDigest, gotAddr1) + assert.Equal(t, OffRampReader.offchainConfigDigest, gotAddr2) }) t.Run("CurrentRateLimiterState", func(t *testing.T) { diff --git a/pkg/loop/internal/relayer/pluginprovider/ext/ccip/test/onramp.go b/pkg/loop/internal/relayer/pluginprovider/ext/ccip/test/onramp.go index 4bbddcd9c5..9ec7ef4a4b 100644 --- a/pkg/loop/internal/relayer/pluginprovider/ext/ccip/test/onramp.go +++ b/pkg/loop/internal/relayer/pluginprovider/ext/ccip/test/onramp.go @@ -131,12 +131,12 @@ func (s staticOnRamp) Evaluate(ctx context.Context, other ccip.OnRampReader) err return fmt.Errorf("expected config %v but got %v", s.dynamicConfigResponse, config) } - sendRequests, err := other.GetSendRequestsBetweenSeqNums(ctx, s.getSendRequestsBetweenSeqNums.SeqNumMin, s.getSendRequestsBetweenSeqNums.SeqNumMax, s.getSendRequestsBetweenSeqNums.Finalized) + sendRequests, err := other.GetSendRequestsBetweenSeqNums(ctx, s.SeqNumMin, s.SeqNumMax, s.Finalized) if err != nil { return fmt.Errorf("failed to get send requests: %w", err) } - if !assert.ObjectsAreEqual(s.getSendRequestsBetweenSeqNumsResponse.EVM2EVMMessageWithTxMeta, sendRequests) { - return fmt.Errorf("expected send requests %v but got %v", s.getSendRequestsBetweenSeqNumsResponse.EVM2EVMMessageWithTxMeta, sendRequests) + if !assert.ObjectsAreEqual(s.EVM2EVMMessageWithTxMeta, sendRequests) { + return fmt.Errorf("expected send requests %v but got %v", s.EVM2EVMMessageWithTxMeta, sendRequests) } isSourceChainHealthy, err := other.IsSourceChainHealthy(ctx) @@ -173,16 +173,16 @@ func (s staticOnRamp) GetDynamicConfig(context.Context) (ccip.OnRampDynamicConfi // GetSendRequestsBetweenSeqNums implements OnRampEvaluator. func (s staticOnRamp) GetSendRequestsBetweenSeqNums(ctx context.Context, seqNumMin uint64, seqNumMax uint64, finalized bool) ([]ccip.EVM2EVMMessageWithTxMeta, error) { - if seqNumMin != s.getSendRequestsBetweenSeqNums.SeqNumMin { - return nil, fmt.Errorf("expected seqNumMin %d but got %d", s.getSendRequestsBetweenSeqNums.SeqNumMin, seqNumMin) + if seqNumMin != s.SeqNumMin { + return nil, fmt.Errorf("expected seqNumMin %d but got %d", s.SeqNumMin, seqNumMin) } - if seqNumMax != s.getSendRequestsBetweenSeqNums.SeqNumMax { - return nil, fmt.Errorf("expected seqNumMax %d but got %d", s.getSendRequestsBetweenSeqNums.SeqNumMax, seqNumMax) + if seqNumMax != s.SeqNumMax { + return nil, fmt.Errorf("expected seqNumMax %d but got %d", s.SeqNumMax, seqNumMax) } - if finalized != s.getSendRequestsBetweenSeqNums.Finalized { - return nil, fmt.Errorf("expected finalized %t but got %t", s.getSendRequestsBetweenSeqNums.Finalized, finalized) + if finalized != s.Finalized { + return nil, fmt.Errorf("expected finalized %t but got %t", s.Finalized, finalized) } - return s.getSendRequestsBetweenSeqNumsResponse.EVM2EVMMessageWithTxMeta, nil + return s.EVM2EVMMessageWithTxMeta, nil } // RouterAddress implements OnRampEvaluator. diff --git a/pkg/loop/internal/relayer/pluginprovider/ext/ccip/test/onramp_test.go b/pkg/loop/internal/relayer/pluginprovider/ext/ccip/test/onramp_test.go index ff1dac78bb..de532a925b 100644 --- a/pkg/loop/internal/relayer/pluginprovider/ext/ccip/test/onramp_test.go +++ b/pkg/loop/internal/relayer/pluginprovider/ext/ccip/test/onramp_test.go @@ -60,10 +60,10 @@ func roundTripOnRampTests(t *testing.T, client cciptypes.OnRampReader) { }) t.Run("GetSendRequestsBetweenSeqNums", func(t *testing.T) { - got, err := client.GetSendRequestsBetweenSeqNums(t.Context(), OnRampReader.getSendRequestsBetweenSeqNums.SeqNumMin, OnRampReader.getSendRequestsBetweenSeqNums.SeqNumMax, OnRampReader.getSendRequestsBetweenSeqNums.Finalized) + got, err := client.GetSendRequestsBetweenSeqNums(t.Context(), OnRampReader.SeqNumMin, OnRampReader.SeqNumMax, OnRampReader.Finalized) require.NoError(t, err) - if !reflect.DeepEqual(OnRampReader.getSendRequestsBetweenSeqNumsResponse.EVM2EVMMessageWithTxMeta, got) { - t.Errorf("expected %v, got %v", OnRampReader.getSendRequestsBetweenSeqNumsResponse.EVM2EVMMessageWithTxMeta, got) + if !reflect.DeepEqual(OnRampReader.EVM2EVMMessageWithTxMeta, got) { + t.Errorf("expected %v, got %v", OnRampReader.EVM2EVMMessageWithTxMeta, got) } }) diff --git a/pkg/loop/internal/relayer/pluginprovider/ext/ccip/test/token_data.go b/pkg/loop/internal/relayer/pluginprovider/ext/ccip/test/token_data.go index ee97af6bbd..3305c96bbe 100644 --- a/pkg/loop/internal/relayer/pluginprovider/ext/ccip/test/token_data.go +++ b/pkg/loop/internal/relayer/pluginprovider/ext/ccip/test/token_data.go @@ -9,14 +9,13 @@ import ( testtypes "github.com/smartcontractkit/chainlink-common/pkg/loop/internal/test/types" "github.com/smartcontractkit/chainlink-common/pkg/types/ccip" - cciptypes "github.com/smartcontractkit/chainlink-common/pkg/types/ccip" ) var TokenDataReader = staticTokenDataReader{ staticTokenDataReaderConfig{ readTokenDataRequest: readTokenDataRequest{ - msg: cciptypes.EVM2EVMOnRampCCIPSendRequestedWithMeta{ - EVM2EVMMessage: cciptypes.EVM2EVMMessage{ + msg: ccip.EVM2EVMOnRampCCIPSendRequestedWithMeta{ + EVM2EVMMessage: ccip.EVM2EVMMessage{ SequenceNumber: 1, GasLimit: big.NewInt(1), Nonce: 1, @@ -51,8 +50,8 @@ var TokenDataReader = staticTokenDataReader{ } type TokenDataReaderEvaluator interface { - cciptypes.TokenDataReader - testtypes.Evaluator[cciptypes.TokenDataReader] + ccip.TokenDataReader + testtypes.Evaluator[ccip.TokenDataReader] } type staticTokenDataReader struct { staticTokenDataReaderConfig @@ -66,7 +65,7 @@ func (s staticTokenDataReader) Close() error { } // Evaluate implements types_test.Evaluator. -func (s staticTokenDataReader) Evaluate(ctx context.Context, other cciptypes.TokenDataReader) error { +func (s staticTokenDataReader) Evaluate(ctx context.Context, other ccip.TokenDataReader) error { got, err := other.ReadTokenData(ctx, s.readTokenDataRequest.msg, s.readTokenDataRequest.tokenIndex) if err != nil { return fmt.Errorf("failed to get other ReadTokenData: %w", err) @@ -78,7 +77,7 @@ func (s staticTokenDataReader) Evaluate(ctx context.Context, other cciptypes.Tok } // ReadTokenData implements ccip.TokenDataReader. -func (s staticTokenDataReader) ReadTokenData(ctx context.Context, msg cciptypes.EVM2EVMOnRampCCIPSendRequestedWithMeta, tokenIndex int) (tokenData []byte, err error) { +func (s staticTokenDataReader) ReadTokenData(ctx context.Context, msg ccip.EVM2EVMOnRampCCIPSendRequestedWithMeta, tokenIndex int) (tokenData []byte, err error) { if !reflect.DeepEqual(s.readTokenDataRequest.msg, msg) { return nil, fmt.Errorf("unexpected msg: wanted %v got %v", s.readTokenDataRequest.msg, msg) } @@ -88,7 +87,7 @@ func (s staticTokenDataReader) ReadTokenData(ctx context.Context, msg cciptypes. return s.readTokenDataResponse, nil } -var _ cciptypes.TokenDataReader = staticTokenDataReader{} +var _ ccip.TokenDataReader = staticTokenDataReader{} type staticTokenDataReaderConfig struct { readTokenDataRequest readTokenDataRequest @@ -96,6 +95,6 @@ type staticTokenDataReaderConfig struct { } type readTokenDataRequest struct { - msg cciptypes.EVM2EVMOnRampCCIPSendRequestedWithMeta + msg ccip.EVM2EVMOnRampCCIPSendRequestedWithMeta tokenIndex int } diff --git a/pkg/loop/internal/relayer/pluginprovider/ext/ccipocr3/convert_test.go b/pkg/loop/internal/relayer/pluginprovider/ext/ccipocr3/convert_test.go index b57d463a90..d40fbbb82c 100644 --- a/pkg/loop/internal/relayer/pluginprovider/ext/ccipocr3/convert_test.go +++ b/pkg/loop/internal/relayer/pluginprovider/ext/ccipocr3/convert_test.go @@ -129,7 +129,7 @@ func TestMessageProtobufFlattening(t *testing.T) { if tc.message.FeeTokenAmount.Int == nil && convertedMessage.FeeTokenAmount.Int == nil { assert.True(t, true, "Both FeeTokenAmount.Int are nil") } else if tc.message.FeeTokenAmount.Int != nil && convertedMessage.FeeTokenAmount.Int != nil { - assert.Equal(t, tc.message.FeeTokenAmount.Int.String(), convertedMessage.FeeTokenAmount.Int.String()) + assert.Equal(t, tc.message.FeeTokenAmount.String(), convertedMessage.FeeTokenAmount.String()) } else { assert.Equal(t, tc.message.FeeTokenAmount.Int, convertedMessage.FeeTokenAmount.Int, "FeeTokenAmount.Int nil mismatch") } @@ -137,7 +137,7 @@ func TestMessageProtobufFlattening(t *testing.T) { if tc.message.FeeValueJuels.Int == nil && convertedMessage.FeeValueJuels.Int == nil { assert.True(t, true, "Both FeeValueJuels.Int are nil") } else if tc.message.FeeValueJuels.Int != nil && convertedMessage.FeeValueJuels.Int != nil { - assert.Equal(t, tc.message.FeeValueJuels.Int.String(), convertedMessage.FeeValueJuels.Int.String()) + assert.Equal(t, tc.message.FeeValueJuels.String(), convertedMessage.FeeValueJuels.String()) } else { assert.Equal(t, tc.message.FeeValueJuels.Int, convertedMessage.FeeValueJuels.Int, "FeeValueJuels.Int nil mismatch") } @@ -149,7 +149,7 @@ func TestMessageProtobufFlattening(t *testing.T) { assert.Equal(t, []byte(original.SourcePoolAddress), []byte(converted.SourcePoolAddress)) assert.Equal(t, []byte(original.DestTokenAddress), []byte(converted.DestTokenAddress)) assert.Equal(t, []byte(original.ExtraData), []byte(converted.ExtraData)) - assert.Equal(t, original.Amount.Int.String(), converted.Amount.Int.String()) + assert.Equal(t, original.Amount.String(), converted.Amount.String()) } }) } @@ -209,7 +209,7 @@ func TestRMNTypesConversion(t *testing.T) { // Verify round-trip conversion assert.Equal(t, tc.rmnReport.ReportVersionDigest, convertedReport.ReportVersionDigest) - assert.Equal(t, tc.rmnReport.DestChainID.Int.String(), convertedReport.DestChainID.Int.String()) + assert.Equal(t, tc.rmnReport.DestChainID.String(), convertedReport.DestChainID.String()) assert.Equal(t, tc.rmnReport.DestChainSelector, convertedReport.DestChainSelector) assert.Equal(t, []byte(tc.rmnReport.RmnRemoteContractAddress), []byte(convertedReport.RmnRemoteContractAddress)) assert.Equal(t, []byte(tc.rmnReport.OfframpAddress), []byte(convertedReport.OfframpAddress)) @@ -262,7 +262,7 @@ func TestProtobufFlatteningRegressionTest(t *testing.T) { assert.Equal(t, []byte(msg.Receiver), []byte(convertedMsg.Receiver), "Receiver corruption indicates protobuf flattening regression") assert.Equal(t, []byte(msg.ExtraArgs), []byte(convertedMsg.ExtraArgs), "ExtraArgs corruption indicates protobuf flattening regression") assert.Equal(t, []byte(msg.FeeToken), []byte(convertedMsg.FeeToken), "FeeToken corruption indicates protobuf flattening regression") - assert.Equal(t, msg.FeeValueJuels.Int.String(), convertedMsg.FeeValueJuels.Int.String(), "FeeValueJuels missing indicates missing field regression") + assert.Equal(t, msg.FeeValueJuels.String(), convertedMsg.FeeValueJuels.String(), "FeeValueJuels missing indicates missing field regression") }) } @@ -727,7 +727,7 @@ func TestTokenPriceMapConversion(t *testing.T) { for token, originalPrice := range tc.priceMap { convertedPrice, exists := convertedMap[token] require.True(t, exists, "token %s should exist in converted map", string(token)) - assert.Equal(t, originalPrice.Int.String(), convertedPrice.Int.String(), "price should survive round-trip for token %s", string(token)) + assert.Equal(t, originalPrice.String(), convertedPrice.String(), "price should survive round-trip for token %s", string(token)) } }) } @@ -843,7 +843,7 @@ func TestMessageTokenIDMapConversion(t *testing.T) { assert.Equal(t, []byte(originalAmount.SourcePoolAddress), []byte(convertedAmount.SourcePoolAddress)) assert.Equal(t, []byte(originalAmount.DestTokenAddress), []byte(convertedAmount.DestTokenAddress)) assert.Equal(t, []byte(originalAmount.ExtraData), []byte(convertedAmount.ExtraData)) - assert.Equal(t, originalAmount.Amount.Int.String(), convertedAmount.Amount.Int.String()) + assert.Equal(t, originalAmount.Amount.String(), convertedAmount.Amount.String()) assert.Equal(t, []byte(originalAmount.DestExecData), []byte(convertedAmount.DestExecData)) } }) @@ -1493,8 +1493,8 @@ func TestPbToBigInt(t *testing.T) { assert.Nil(t, result.Int, "result.Int should be nil when expected is nil") } else { assert.NotNil(t, result.Int, "result.Int should not be nil when expected is not nil") - assert.Equal(t, tc.expected.Int.String(), result.Int.String(), "converted BigInt should match expected value") - assert.Equal(t, tc.expected.Int.Cmp(result.Int), 0, "BigInt comparison should be equal") + assert.Equal(t, tc.expected.String(), result.String(), "converted BigInt should match expected value") + assert.Equal(t, tc.expected.Cmp(result.Int), 0, "BigInt comparison should be equal") } }) } @@ -1620,8 +1620,8 @@ func TestPbToBigIntRoundTrip(t *testing.T) { assert.Nil(t, convertedValue.Int, "nil should round-trip to nil") } else { assert.NotNil(t, convertedValue.Int, "converted value should not be nil for non-nil input") - assert.Equal(t, originalValue.Int.String(), convertedValue.Int.String(), "round-trip conversion should preserve value") - assert.Equal(t, originalValue.Int.Cmp(convertedValue.Int), 0, "round-trip BigInt comparison should be equal") + assert.Equal(t, originalValue.String(), convertedValue.String(), "round-trip conversion should preserve value") + assert.Equal(t, originalValue.Cmp(convertedValue.Int), 0, "round-trip BigInt comparison should be equal") } }) } @@ -1637,7 +1637,7 @@ func TestPbBigIntEdgeCases(t *testing.T) { result2 := pbToBigInt(input) assert.Equal(t, big.NewInt(0).String(), result1.String()) - assert.Equal(t, big.NewInt(0).String(), result2.Int.String()) + assert.Equal(t, big.NewInt(0).String(), result2.String()) }) t.Run("single zero byte should equal zero", func(t *testing.T) { @@ -1647,7 +1647,7 @@ func TestPbBigIntEdgeCases(t *testing.T) { result2 := pbToBigInt(input) assert.Equal(t, big.NewInt(0).String(), result1.String()) - assert.Equal(t, big.NewInt(0).String(), result2.Int.String()) + assert.Equal(t, big.NewInt(0).String(), result2.String()) }) t.Run("multiple zero bytes should equal zero", func(t *testing.T) { @@ -1657,7 +1657,7 @@ func TestPbBigIntEdgeCases(t *testing.T) { result2 := pbToBigInt(input) assert.Equal(t, big.NewInt(0).String(), result1.String()) - assert.Equal(t, big.NewInt(0).String(), result2.Int.String()) + assert.Equal(t, big.NewInt(0).String(), result2.String()) }) t.Run("large byte array should work correctly", func(t *testing.T) { @@ -1673,7 +1673,7 @@ func TestPbBigIntEdgeCases(t *testing.T) { expected := new(big.Int).SetBytes(bytes) assert.Equal(t, expected.String(), result1.String()) - assert.Equal(t, expected.String(), result2.Int.String()) + assert.Equal(t, expected.String(), result2.String()) }) } @@ -1701,7 +1701,7 @@ func TestPbBigIntConsistency(t *testing.T) { // (except pbToBigInt may preserve nil differently) if input != nil { if result2.Int != nil { - assert.Equal(t, result1.String(), result2.Int.String(), + assert.Equal(t, result1.String(), result2.String(), "pbBigIntToInt and pbToBigInt should produce equivalent numeric results") } } diff --git a/pkg/loop/internal/relayer/pluginprovider/ext/ccipocr3/test/chain_accessor.go b/pkg/loop/internal/relayer/pluginprovider/ext/ccipocr3/test/chain_accessor.go index 40c5d99d34..e9ccc82a80 100644 --- a/pkg/loop/internal/relayer/pluginprovider/ext/ccipocr3/test/chain_accessor.go +++ b/pkg/loop/internal/relayer/pluginprovider/ext/ccipocr3/test/chain_accessor.go @@ -309,7 +309,6 @@ type staticChainAccessor struct { } func newStaticChainAccessor(lggr logger.Logger, cfg staticChainAccessorConfig) staticChainAccessor { - lggr = logger.Named(lggr, "staticChainAccessor") return staticChainAccessor{ staticChainAccessorConfig: cfg, } diff --git a/pkg/loop/internal/relayer/pluginprovider/ext/ccipocr3/test/codec_components.go b/pkg/loop/internal/relayer/pluginprovider/ext/ccipocr3/test/codec_components.go index b41028755a..afbf07d497 100644 --- a/pkg/loop/internal/relayer/pluginprovider/ext/ccipocr3/test/codec_components.go +++ b/pkg/loop/internal/relayer/pluginprovider/ext/ccipocr3/test/codec_components.go @@ -49,7 +49,6 @@ type staticChainSpecificAddressCodec struct { } func newStaticChainSpecificAddressCodec(lggr logger.Logger, cfg staticChainSpecificAddressCodecConfig) staticChainSpecificAddressCodec { - lggr = logger.Named(lggr, "staticChainSpecificAddressCodec") return staticChainSpecificAddressCodec{ staticChainSpecificAddressCodecConfig: cfg, } @@ -165,7 +164,6 @@ type staticCommitPluginCodec struct { } func newStaticCommitPluginCodec(lggr logger.Logger, cfg staticCommitPluginCodecConfig) staticCommitPluginCodec { - lggr = logger.Named(lggr, "staticCommitPluginCodec") return staticCommitPluginCodec{ staticCommitPluginCodecConfig: cfg, } diff --git a/pkg/loop/internal/relayer/pluginprovider/ext/ccipocr3/test/codec_test.go b/pkg/loop/internal/relayer/pluginprovider/ext/ccipocr3/test/codec_test.go index 23a0a852ab..001c3250d2 100644 --- a/pkg/loop/internal/relayer/pluginprovider/ext/ccipocr3/test/codec_test.go +++ b/pkg/loop/internal/relayer/pluginprovider/ext/ccipocr3/test/codec_test.go @@ -19,19 +19,19 @@ func TestCodec(t *testing.T) { t.Run("ChainSpecificAddressCodec", func(t *testing.T) { // Test that the embedded ChainSpecificAddressCodec works - result, err := codec.ChainSpecificAddressCodec.AddressBytesToString([]byte("test")) + result, err := codec.AddressBytesToString([]byte("test")) assert.NoError(t, err) assert.Equal(t, "test-address", result) - bytes, err := codec.ChainSpecificAddressCodec.AddressStringToBytes("test") + bytes, err := codec.AddressStringToBytes("test") assert.NoError(t, err) assert.Equal(t, []byte("test-address"), bytes) - oracleBytes, err := codec.ChainSpecificAddressCodec.OracleIDAsAddressBytes(42) + oracleBytes, err := codec.OracleIDAsAddressBytes(42) assert.NoError(t, err) assert.Equal(t, []byte{42}, oracleBytes) - transmitter, err := codec.ChainSpecificAddressCodec.TransmitterBytesToString([]byte("test")) + transmitter, err := codec.TransmitterBytesToString([]byte("test")) assert.NoError(t, err) assert.Equal(t, "test-transmitter", transmitter) }) @@ -65,7 +65,7 @@ func TestCodec(t *testing.T) { message := ccipocr3.Bytes("test-message") attestation := ccipocr3.Bytes("test-attestation") - encoded, err := codec.TokenDataEncoder.EncodeUSDC(ctx, message, attestation) + encoded, err := codec.EncodeUSDC(ctx, message, attestation) assert.NoError(t, err) assert.Equal(t, ccipocr3.Bytes("encoded-usdc"), encoded) }) @@ -73,13 +73,13 @@ func TestCodec(t *testing.T) { t.Run("SourceChainExtraDataCodec", func(t *testing.T) { // Test that the embedded SourceChainExtraDataCodec works extraArgs := ccipocr3.Bytes("test-extra-args") - result, err := codec.SourceChainExtraDataCodec.DecodeExtraArgsToMap(extraArgs) + result, err := codec.DecodeExtraArgsToMap(extraArgs) assert.NoError(t, err) assert.NotNil(t, result) assert.Contains(t, result, "gasLimit") destExecData := ccipocr3.Bytes("test-dest-exec-data") - result2, err := codec.SourceChainExtraDataCodec.DecodeDestExecDataToMap(destExecData) + result2, err := codec.DecodeDestExecDataToMap(destExecData) assert.NoError(t, err) assert.NotNil(t, result2) assert.Contains(t, result2, "data") @@ -152,17 +152,17 @@ func TestCodecIntegration(t *testing.T) { // Test address conversion workflow testAddress := "0x1234567890abcdef" - addressBytes, err := codec.ChainSpecificAddressCodec.AddressStringToBytes(testAddress) + addressBytes, err := codec.AddressStringToBytes(testAddress) require.NoError(t, err) assert.NotEmpty(t, addressBytes) - addressString, err := codec.ChainSpecificAddressCodec.AddressBytesToString(addressBytes) + addressString, err := codec.AddressBytesToString(addressBytes) require.NoError(t, err) assert.NotEmpty(t, addressString) // Test oracle ID to address conversion oracleID := uint8(42) - oracleAddress, err := codec.ChainSpecificAddressCodec.OracleIDAsAddressBytes(oracleID) + oracleAddress, err := codec.OracleIDAsAddressBytes(oracleID) require.NoError(t, err) assert.Equal(t, []byte{42}, oracleAddress) }) @@ -172,7 +172,7 @@ func TestCodecIntegration(t *testing.T) { message := ccipocr3.Bytes("test-usdc-message") attestation := ccipocr3.Bytes("test-usdc-attestation") - encodedUSDC, err := codec.TokenDataEncoder.EncodeUSDC(ctx, message, attestation) + encodedUSDC, err := codec.EncodeUSDC(ctx, message, attestation) require.NoError(t, err) assert.NotEmpty(t, encodedUSDC) assert.Equal(t, ccipocr3.Bytes("encoded-usdc"), encodedUSDC) @@ -181,12 +181,12 @@ func TestCodecIntegration(t *testing.T) { t.Run("ExtraDataWorkflow", func(t *testing.T) { // Test extra data decoding workflow extraArgs := ccipocr3.Bytes("{\"gasLimit\": 100000}") - argsMap, err := codec.SourceChainExtraDataCodec.DecodeExtraArgsToMap(extraArgs) + argsMap, err := codec.DecodeExtraArgsToMap(extraArgs) require.NoError(t, err) assert.NotEmpty(t, argsMap) destExecData := ccipocr3.Bytes("{\"data\": \"test\"}") - execMap, err := codec.SourceChainExtraDataCodec.DecodeDestExecDataToMap(destExecData) + execMap, err := codec.DecodeDestExecDataToMap(destExecData) require.NoError(t, err) assert.NotEmpty(t, execMap) }) diff --git a/pkg/loop/internal/relayer/pluginprovider/ext/ccipocr3/test/provider_test.go b/pkg/loop/internal/relayer/pluginprovider/ext/ccipocr3/test/provider_test.go index 9209a0cc02..03fccfc854 100644 --- a/pkg/loop/internal/relayer/pluginprovider/ext/ccipocr3/test/provider_test.go +++ b/pkg/loop/internal/relayer/pluginprovider/ext/ccipocr3/test/provider_test.go @@ -45,11 +45,11 @@ func TestCCIPProvider(t *testing.T) { codec := provider.Codec() // Test ChainSpecificAddressCodec - addrStr, err := codec.ChainSpecificAddressCodec.AddressBytesToString([]byte("test")) + addrStr, err := codec.AddressBytesToString([]byte("test")) assert.NoError(t, err) assert.NotEmpty(t, addrStr) - addrBytes, err := codec.ChainSpecificAddressCodec.AddressStringToBytes("test") + addrBytes, err := codec.AddressStringToBytes("test") assert.NoError(t, err) assert.NotNil(t, addrBytes) @@ -70,16 +70,16 @@ func TestCCIPProvider(t *testing.T) { assert.NoError(t, err) // Test TokenDataEncoder - encodedUSDC, err := codec.TokenDataEncoder.EncodeUSDC(ctx, []byte("message"), []byte("attestation")) + encodedUSDC, err := codec.EncodeUSDC(ctx, []byte("message"), []byte("attestation")) assert.NoError(t, err) assert.NotNil(t, encodedUSDC) // Test SourceChainExtraDataCodec - extraArgs, err := codec.SourceChainExtraDataCodec.DecodeExtraArgsToMap([]byte("test-extra-args")) + extraArgs, err := codec.DecodeExtraArgsToMap([]byte("test-extra-args")) assert.NoError(t, err) assert.NotNil(t, extraArgs) - destExecData, err := codec.SourceChainExtraDataCodec.DecodeDestExecDataToMap([]byte("test-dest-exec-data")) + destExecData, err := codec.DecodeDestExecDataToMap([]byte("test-dest-exec-data")) assert.NoError(t, err) assert.NotNil(t, destExecData) @@ -112,7 +112,7 @@ func TestCCIPProvider(t *testing.T) { }, } - hash, err := codec.MessageHasher.Hash(ctx, testMessage) + hash, err := codec.Hash(ctx, testMessage) assert.NoError(t, err) assert.NotNil(t, hash) } diff --git a/pkg/loop/internal/relayer/pluginprovider/ext/median/test/median.go b/pkg/loop/internal/relayer/pluginprovider/ext/median/test/median.go index b6f5dc5c6c..0a5413785c 100644 --- a/pkg/loop/internal/relayer/pluginprovider/ext/median/test/median.go +++ b/pkg/loop/internal/relayer/pluginprovider/ext/median/test/median.go @@ -145,7 +145,7 @@ func (s staticMedianFactoryServer) NewMedianFactory(ctx context.Context, provide var compareError *CompareError isCompareError := errors.As(err, &compareError) // allow 0 as valid data source value with the same staticMedianFactoryServer (because it is only defined once as a global var for all tests) - if !(isCompareError && compareError.GotZero()) { + if !isCompareError || !compareError.GotZero() { return nil, fmt.Errorf("NewMedianFactory: gasPriceSubunitsDataSource does not equal a static gas price subunits data source implementation: %w", err) } } @@ -278,12 +278,12 @@ func (s staticMedianProvider) AssertEqual(ctx context.Context, t *testing.T, pro t.Run("ContractConfigTracker", func(t *testing.T) { t.Parallel() - assert.NoError(t, s.staticMedianProviderConfig.contractTracker.Evaluate(ctx, provider.ContractConfigTracker())) + assert.NoError(t, s.contractTracker.Evaluate(ctx, provider.ContractConfigTracker())) }) t.Run("ContractTransmitter", func(t *testing.T) { t.Parallel() - assert.NoError(t, s.staticMedianProviderConfig.contractTransmitter.Evaluate(ctx, provider.ContractTransmitter())) + assert.NoError(t, s.contractTransmitter.Evaluate(ctx, provider.ContractTransmitter())) }) t.Run("ReportCodec", func(t *testing.T) { @@ -316,7 +316,7 @@ func (s staticMedianProvider) Evaluate(ctx context.Context, provider types.Media } ct := provider.ContractTransmitter() - err = s.staticMedianProviderConfig.contractTransmitter.Evaluate(ctx, ct) + err = s.contractTransmitter.Evaluate(ctx, ct) if err != nil { return fmt.Errorf("providers contract transmitter does not equal static contract transmitter: %w", err) } diff --git a/pkg/loop/internal/relayer/pluginprovider/ext/mercury/test/ocr_plugin.go b/pkg/loop/internal/relayer/pluginprovider/ext/mercury/test/ocr_plugin.go index 9ef835e105..949dadf975 100644 --- a/pkg/loop/internal/relayer/pluginprovider/ext/mercury/test/ocr_plugin.go +++ b/pkg/loop/internal/relayer/pluginprovider/ext/mercury/test/ocr_plugin.go @@ -77,7 +77,7 @@ func (s staticMercuryPlugin) Observation(ctx context.Context, timestamp libocr.R if !bytes.Equal(previousReport, s.observationRequest.previousReport) { return nil, fmt.Errorf("expected previous report %x but got %x", s.observationRequest.previousReport, previousReport) } - return s.observationResponse.observation, nil + return s.observation, nil } func (s staticMercuryPlugin) Report(ctx context.Context, timestamp libocr.ReportTimestamp, previousReport libocr.Report, observations []libocr.AttributedObservation) (bool, libocr.Report, error) { @@ -87,10 +87,10 @@ func (s staticMercuryPlugin) Report(ctx context.Context, timestamp libocr.Report if !bytes.Equal(s.reportRequest.previousReport, previousReport) { return false, nil, fmt.Errorf("expected previous report %x but got %x", s.reportRequest.previousReport, previousReport) } - if !assert.ObjectsAreEqual(s.reportRequest.observations, observations) { - return false, nil, fmt.Errorf("expected %v but got %v", s.reportRequest.observations, observations) + if !assert.ObjectsAreEqual(s.observations, observations) { + return false, nil, fmt.Errorf("expected %v but got %v", s.observations, observations) } - return s.reportResponse.shouldReport, s.reportResponse.report, nil + return s.shouldReport, s.report, nil } func (s staticMercuryPlugin) Close() error { return nil } @@ -98,9 +98,9 @@ func (s staticMercuryPlugin) Close() error { return nil } func (s staticMercuryPlugin) AssertEqual(ctx context.Context, t *testing.T, other ocr3types.MercuryPlugin) { gotObs, err := other.Observation(ctx, s.observationRequest.reportTimestamp, s.observationRequest.previousReport) require.NoError(t, err) - assert.Equal(t, s.observationResponse.observation, gotObs) - gotOk, gotReport, err := other.Report(ctx, s.reportRequest.reportTimestamp, s.reportRequest.previousReport, s.reportRequest.observations) + assert.Equal(t, s.observation, gotObs) + gotOk, gotReport, err := other.Report(ctx, s.reportRequest.reportTimestamp, s.reportRequest.previousReport, s.observations) require.NoError(t, err) - assert.Equal(t, s.reportResponse.shouldReport, gotOk) - assert.Equal(t, s.reportResponse.report, gotReport) + assert.Equal(t, s.shouldReport, gotOk) + assert.Equal(t, s.report, gotReport) } diff --git a/pkg/loop/internal/relayer/pluginprovider/ocr2/contract_transmitter.go b/pkg/loop/internal/relayer/pluginprovider/ocr2/contract_transmitter.go index 323f73207b..713d16d60e 100644 --- a/pkg/loop/internal/relayer/pluginprovider/ocr2/contract_transmitter.go +++ b/pkg/loop/internal/relayer/pluginprovider/ocr2/contract_transmitter.go @@ -23,9 +23,9 @@ func (c *contractTransmitterClient) Transmit(ctx context.Context, reportContext req := &pb.TransmitRequest{ ReportContext: &pb.ReportContext{ ReportTimestamp: &pb.ReportTimestamp{ - ConfigDigest: reportContext.ReportTimestamp.ConfigDigest[:], - Epoch: reportContext.ReportTimestamp.Epoch, - Round: uint32(reportContext.ReportTimestamp.Round), + ConfigDigest: reportContext.ConfigDigest[:], + Epoch: reportContext.Epoch, + Round: uint32(reportContext.Round), }, ExtraHash: reportContext.ExtraHash[:], }, diff --git a/pkg/loop/internal/relayerset/relayer.go b/pkg/loop/internal/relayerset/relayer.go index 52bea27aa6..d80de1f6f0 100644 --- a/pkg/loop/internal/relayerset/relayer.go +++ b/pkg/loop/internal/relayerset/relayer.go @@ -63,7 +63,7 @@ func (r *relayer) NewContractWriter(_ context.Context, contractWriterConfig []by } return contractWriterID, nil, nil }) - return contractwriter.NewClient(r.relayerSetClient.BrokerExt.WithName("ContractWriterClient"), cwc), nil + return contractwriter.NewClient(r.relayerSetClient.WithName("ContractWriterClient"), cwc), nil } func (r *relayer) Start(ctx context.Context) error { diff --git a/pkg/loop/internal/relayerset/relayerset_test.go b/pkg/loop/internal/relayerset/relayerset_test.go index 986fa564dd..49c5ce3145 100644 --- a/pkg/loop/internal/relayerset/relayerset_test.go +++ b/pkg/loop/internal/relayerset/relayerset_test.go @@ -22,7 +22,6 @@ import ( evmtypes "github.com/smartcontractkit/chainlink-common/pkg/types/chains/evm" soltypes "github.com/smartcontractkit/chainlink-common/pkg/types/chains/solana" "github.com/smartcontractkit/chainlink-common/pkg/types/chains/ton" - tontypes "github.com/smartcontractkit/chainlink-common/pkg/types/chains/ton" "github.com/smartcontractkit/chainlink-common/pkg/types/core" "github.com/smartcontractkit/chainlink-common/pkg/types/core/mocks" mocks2 "github.com/smartcontractkit/chainlink-common/pkg/types/mocks" @@ -661,7 +660,7 @@ func Test_RelayerSet_SolanaService(t *testing.T) { out, err := sol.GetAccountInfoWithOpts(ctx, req) require.NoError(t, err) require.Equal(t, lamports, out.Value.Lamports) - require.Equal(t, slot, out.RPCContext.Slot) + require.Equal(t, slot, out.Slot) }, }, { @@ -1277,48 +1276,48 @@ func Test_RelayerSet_TONService(t *testing.T) { }{ { name: "GetMasterchainInfo", - run: func(t *testing.T, ton types.TONService, mockTON *mocks2.TONService) { - blockIDExt := &tontypes.BlockIDExt{ + run: func(t *testing.T, ts types.TONService, mockTON *mocks2.TONService) { + blockIDExt := &ton.BlockIDExt{ Workchain: 0, Shard: 123, SeqNo: 1, } mockTON.EXPECT().GetMasterchainInfo(mock.Anything).Return(blockIDExt, nil) - out, err := ton.GetMasterchainInfo(ctx) + out, err := ts.GetMasterchainInfo(ctx) require.NoError(t, err) require.Equal(t, blockIDExt, out) }, }, { name: "GetBlockData", - run: func(t *testing.T, ton types.TONService, mockTON *mocks2.TONService) { - blockIDExt := &tontypes.BlockIDExt{Workchain: 0, Shard: 1, SeqNo: 100} - block := &tontypes.Block{GlobalID: -217} + run: func(t *testing.T, ts types.TONService, mockTON *mocks2.TONService) { + blockIDExt := &ton.BlockIDExt{Workchain: 0, Shard: 1, SeqNo: 100} + block := &ton.Block{GlobalID: -217} mockTON.EXPECT().GetBlockData(mock.Anything, blockIDExt).Return(block, nil) - out, err := ton.GetBlockData(ctx, blockIDExt) + out, err := ts.GetBlockData(ctx, blockIDExt) require.NoError(t, err) require.Equal(t, block, out) }, }, { name: "GetAccountBalance", - run: func(t *testing.T, ton types.TONService, mockTON *mocks2.TONService) { + run: func(t *testing.T, ts types.TONService, mockTON *mocks2.TONService) { addr := "0:abc123" - blockID := &tontypes.BlockIDExt{Workchain: 0, Shard: 1, SeqNo: 100} - balance := &tontypes.Balance{} + blockID := &ton.BlockIDExt{Workchain: 0, Shard: 1, SeqNo: 100} + balance := &ton.Balance{} mockTON.EXPECT().GetAccountBalance(mock.Anything, addr, blockID).Return(balance, nil) - out, err := ton.GetAccountBalance(ctx, addr, blockID) + out, err := ts.GetAccountBalance(ctx, addr, blockID) require.NoError(t, err) require.Equal(t, balance, out) }, }, { name: "SendTx", - run: func(t *testing.T, ton types.TONService, mockTON *mocks2.TONService) { + run: func(t *testing.T, ts types.TONService, mockTON *mocks2.TONService) { addr := "0:abc123" body := []byte("body") stateInit := []byte("state-init") - msg := tontypes.Message{ + msg := ton.Message{ Mode: 1, ToAddress: addr, Amount: "1.0", @@ -1327,18 +1326,18 @@ func Test_RelayerSet_TONService(t *testing.T) { StateInit: stateInit, } mockTON.EXPECT().SendTx(mock.Anything, msg).Return(nil) - err := ton.SendTx(ctx, msg) + err := ts.SendTx(ctx, msg) require.NoError(t, err) }, }, { name: "GetTxStatus", - run: func(t *testing.T, ton types.TONService, mockTON *mocks2.TONService) { + run: func(t *testing.T, ts types.TONService, mockTON *mocks2.TONService) { lt := uint64(123456) status := types.Finalized - exitCode := tontypes.ExitCode(0) + exitCode := ton.ExitCode(0) mockTON.EXPECT().GetTxStatus(mock.Anything, lt).Return(status, exitCode, nil) - s, c, err := ton.GetTxStatus(ctx, lt) + s, c, err := ts.GetTxStatus(ctx, lt) require.NoError(t, err) require.Equal(t, status, s) require.Equal(t, exitCode, c) @@ -1346,11 +1345,11 @@ func Test_RelayerSet_TONService(t *testing.T) { }, { name: "GetTxExecutionFees", - run: func(t *testing.T, ton types.TONService, mockTON *mocks2.TONService) { + run: func(t *testing.T, ts types.TONService, mockTON *mocks2.TONService) { lt := uint64(123456) - fees := &tontypes.TransactionFee{TransactionFee: big.NewInt(100)} + fees := &ton.TransactionFee{TransactionFee: big.NewInt(100)} mockTON.EXPECT().GetTxExecutionFees(mock.Anything, lt).Return(fees, nil) - out, err := ton.GetTxExecutionFees(ctx, lt) + out, err := ts.GetTxExecutionFees(ctx, lt) require.NoError(t, err) require.Equal(t, fees, out) }, @@ -1366,10 +1365,10 @@ func Test_RelayerSet_TONService(t *testing.T) { }, { name: "RegisterFilter", - run: func(t *testing.T, ton types.TONService, mockTON *mocks2.TONService) { - filter := tontypes.LPFilterQuery{Name: "filter1"} + run: func(t *testing.T, ts types.TONService, mockTON *mocks2.TONService) { + filter := ton.LPFilterQuery{Name: "filter1"} mockTON.EXPECT().RegisterFilter(mock.Anything, filter).Return(nil) - err := ton.RegisterFilter(ctx, filter) + err := ts.RegisterFilter(ctx, filter) require.NoError(t, err) }, }, @@ -1453,15 +1452,15 @@ type TestTON struct { mockedTONService *mocks2.TONService } -func (t *TestTON) GetMasterchainInfo(ctx context.Context) (*tontypes.BlockIDExt, error) { +func (t *TestTON) GetMasterchainInfo(ctx context.Context) (*ton.BlockIDExt, error) { return t.mockedTONService.GetMasterchainInfo(ctx) } -func (t *TestTON) GetBlockData(ctx context.Context, block *tontypes.BlockIDExt) (*tontypes.Block, error) { +func (t *TestTON) GetBlockData(ctx context.Context, block *ton.BlockIDExt) (*ton.Block, error) { return t.mockedTONService.GetBlockData(ctx, block) } -func (t *TestTON) GetAccountBalance(ctx context.Context, address string, block *tontypes.BlockIDExt) (*tontypes.Balance, error) { +func (t *TestTON) GetAccountBalance(ctx context.Context, address string, block *ton.BlockIDExt) (*ton.Balance, error) { return t.mockedTONService.GetAccountBalance(ctx, address, block) } diff --git a/pkg/loop/internal/reportingplugin/median/median.go b/pkg/loop/internal/reportingplugin/median/median.go index 5fc7820fae..cfff851e35 100644 --- a/pkg/loop/internal/reportingplugin/median/median.go +++ b/pkg/loop/internal/reportingplugin/median/median.go @@ -108,7 +108,7 @@ func (m *PluginMedianClient) NewMedianFactory(ctx context.Context, provider type } return reply.ReportingPluginFactoryID, nil, nil }) - return ocr2.NewReportingPluginFactoryClient(m.PluginClient.BrokerExt, cc), nil + return ocr2.NewReportingPluginFactoryClient(m.BrokerExt, cc), nil } var _ pb.PluginMedianServer = (*pluginMedianServer)(nil) diff --git a/pkg/loop/internal/reportingplugin/mercury/mercury.go b/pkg/loop/internal/reportingplugin/mercury/mercury.go index 07cde5774d..b004045075 100644 --- a/pkg/loop/internal/reportingplugin/mercury/mercury.go +++ b/pkg/loop/internal/reportingplugin/mercury/mercury.go @@ -91,7 +91,7 @@ func (c *AdapterClient) NewMercuryV1Factory(ctx context.Context, } cc := c.NewClientConn("MercuryV3Factory", newMercuryClientFn) - return NewPluginFactoryClient(c.PluginClient.BrokerExt, cc), nil + return NewPluginFactoryClient(c.BrokerExt, cc), nil } func (c *AdapterClient) NewMercuryV2Factory(ctx context.Context, @@ -139,7 +139,7 @@ func (c *AdapterClient) NewMercuryV2Factory(ctx context.Context, } cc := c.NewClientConn("MercuryV2Factory", newMercuryClientFn) - return NewPluginFactoryClient(c.PluginClient.BrokerExt, cc), nil + return NewPluginFactoryClient(c.BrokerExt, cc), nil } func (c *AdapterClient) NewMercuryV3Factory(ctx context.Context, @@ -189,7 +189,7 @@ func (c *AdapterClient) NewMercuryV3Factory(ctx context.Context, } cc := c.NewClientConn("MercuryV3Factory", newMercuryClientFn) - return NewPluginFactoryClient(c.PluginClient.BrokerExt, cc), nil + return NewPluginFactoryClient(c.BrokerExt, cc), nil } func (c *AdapterClient) NewMercuryV4Factory(ctx context.Context, @@ -239,7 +239,7 @@ func (c *AdapterClient) NewMercuryV4Factory(ctx context.Context, } cc := c.NewClientConn("MercuryV4Factory", newMercuryClientFn) - return NewPluginFactoryClient(c.PluginClient.BrokerExt, cc), nil + return NewPluginFactoryClient(c.BrokerExt, cc), nil } var _ mercurypb.MercuryAdapterServer = (*AdapterServer)(nil) diff --git a/pkg/loop/internal/reportingplugin/mercury/mercury_reporting.go b/pkg/loop/internal/reportingplugin/mercury/mercury_reporting.go index fd8bab4226..674a46a4c4 100644 --- a/pkg/loop/internal/reportingplugin/mercury/mercury_reporting.go +++ b/pkg/loop/internal/reportingplugin/mercury/mercury_reporting.go @@ -48,7 +48,7 @@ func (r *PluginFactoryClient) NewMercuryPlugin(ctx context.Context, config ocr3t MaxReportLength: int(response.MercuryPluginInfo.MercuryPluginLimits.MaxReportLength), }, } - cc, err := r.BrokerExt.Dial(response.MercuryPluginID) + cc, err := r.Dial(response.MercuryPluginID) if err != nil { return nil, ocr3types.MercuryPluginInfo{}, err } diff --git a/pkg/loop/internal/reportingplugin/test/reporting.go b/pkg/loop/internal/reportingplugin/test/reporting.go index 1b7c9e6a61..d5a773d3cc 100644 --- a/pkg/loop/internal/reportingplugin/test/reporting.go +++ b/pkg/loop/internal/reportingplugin/test/reporting.go @@ -30,15 +30,15 @@ type staticReportingPlugin struct { } func (s staticReportingPlugin) Query(ctx context.Context, timestamp libocr.ReportTimestamp) (libocr.Query, error) { - if timestamp != s.staticReportingPluginConfig.ReportContext.ReportTimestamp { - return nil, errExpected(s.staticReportingPluginConfig.ReportContext.ReportTimestamp, timestamp) + if timestamp != s.ReportContext.ReportTimestamp { + return nil, errExpected(s.ReportContext.ReportTimestamp, timestamp) } return s.staticReportingPluginConfig.Query, nil } func (s staticReportingPlugin) Observation(ctx context.Context, timestamp libocr.ReportTimestamp, q libocr.Query) (libocr.Observation, error) { - if timestamp != s.staticReportingPluginConfig.ReportContext.ReportTimestamp { - return nil, errExpected(s.staticReportingPluginConfig.ReportContext.ReportTimestamp, timestamp) + if timestamp != s.ReportContext.ReportTimestamp { + return nil, errExpected(s.ReportContext.ReportTimestamp, timestamp) } if !bytes.Equal(q, s.staticReportingPluginConfig.Query) { return nil, errExpected(s.staticReportingPluginConfig.Query, q) @@ -47,21 +47,21 @@ func (s staticReportingPlugin) Observation(ctx context.Context, timestamp libocr } func (s staticReportingPlugin) Report(ctx context.Context, timestamp libocr.ReportTimestamp, q libocr.Query, observations []libocr.AttributedObservation) (bool, libocr.Report, error) { - if timestamp != s.staticReportingPluginConfig.ReportContext.ReportTimestamp { - return false, nil, errExpected(s.staticReportingPluginConfig.ReportContext.ReportTimestamp, timestamp) + if timestamp != s.ReportContext.ReportTimestamp { + return false, nil, errExpected(s.ReportContext.ReportTimestamp, timestamp) } if !bytes.Equal(q, s.staticReportingPluginConfig.Query) { return false, nil, errExpected(s.staticReportingPluginConfig.Query, q) } - if !assert.ObjectsAreEqual(s.staticReportingPluginConfig.AttributedObservations, observations) { - return false, nil, errExpected(s.staticReportingPluginConfig.AttributedObservations, observations) + if !assert.ObjectsAreEqual(s.AttributedObservations, observations) { + return false, nil, errExpected(s.AttributedObservations, observations) } - return s.staticReportingPluginConfig.ShouldReport, s.staticReportingPluginConfig.Report, nil + return s.ShouldReport, s.staticReportingPluginConfig.Report, nil } func (s staticReportingPlugin) ShouldAcceptFinalizedReport(ctx context.Context, timestamp libocr.ReportTimestamp, r libocr.Report) (bool, error) { - if timestamp != s.staticReportingPluginConfig.ReportContext.ReportTimestamp { - return false, errExpected(s.staticReportingPluginConfig.ReportContext.ReportTimestamp, timestamp) + if timestamp != s.ReportContext.ReportTimestamp { + return false, errExpected(s.ReportContext.ReportTimestamp, timestamp) } if !bytes.Equal(r, s.staticReportingPluginConfig.Report) { return false, errExpected(s.staticReportingPluginConfig.Report, r) @@ -70,8 +70,8 @@ func (s staticReportingPlugin) ShouldAcceptFinalizedReport(ctx context.Context, } func (s staticReportingPlugin) ShouldTransmitAcceptedReport(ctx context.Context, timestamp libocr.ReportTimestamp, r libocr.Report) (bool, error) { - if timestamp != s.staticReportingPluginConfig.ReportContext.ReportTimestamp { - return false, errExpected(s.staticReportingPluginConfig.ReportContext.ReportTimestamp, timestamp) + if timestamp != s.ReportContext.ReportTimestamp { + return false, errExpected(s.ReportContext.ReportTimestamp, timestamp) } if !bytes.Equal(r, s.staticReportingPluginConfig.Report) { return false, errExpected(s.staticReportingPluginConfig.Report, r) diff --git a/pkg/loop/median_service_test.go b/pkg/loop/median_service_test.go index 690100bb55..bf05c7fcf0 100644 --- a/pkg/loop/median_service_test.go +++ b/pkg/loop/median_service_test.go @@ -22,7 +22,7 @@ func TestMedianService(t *testing.T) { median := loop.NewMedianService(lggr, loop.GRPCOpts{}, func() *exec.Cmd { return NewHelperProcessCommand(loop.PluginMedianName, false, 0) }, mediantest.MedianProvider(lggr), mediantest.MedianContractID, mediantest.DataSource, mediantest.JuelsPerFeeCoinDataSource, mediantest.GasPriceSubunitsDataSource, errorlogtest.ErrorLog, nil) - hook := median.PluginService.XXXTestHook() + hook := median.XXXTestHook() servicetest.Run(t, median) t.Run("control", func(t *testing.T) { diff --git a/pkg/loop/mercury_service_test.go b/pkg/loop/mercury_service_test.go index aa6d231edd..eef0f6b636 100644 --- a/pkg/loop/mercury_service_test.go +++ b/pkg/loop/mercury_service_test.go @@ -24,7 +24,7 @@ func TestMercuryV4Service(t *testing.T) { mercuryV4 := loop.NewMercuryV4Service(lggr, loop.GRPCOpts{}, func() *exec.Cmd { return NewHelperProcessCommand(loop.PluginMercuryName, true, 0) }, mercurytest.MercuryProvider(lggr), mercuryv4test.DataSource) - hook := mercuryV4.PluginService.XXXTestHook() + hook := mercuryV4.XXXTestHook() servicetest.Run(t, mercuryV4) t.Run("control", func(t *testing.T) { @@ -73,7 +73,7 @@ func TestMercuryV3Service(t *testing.T) { mercuryV3 := loop.NewMercuryV3Service(lggr, loop.GRPCOpts{}, func() *exec.Cmd { return NewHelperProcessCommand(loop.PluginMercuryName, true, 0) }, mercurytest.MercuryProvider(lggr), mercuryv3test.DataSource) - hook := mercuryV3.PluginService.XXXTestHook() + hook := mercuryV3.XXXTestHook() servicetest.Run(t, mercuryV3) t.Run("control", func(t *testing.T) { @@ -122,7 +122,7 @@ func TestMercuryV1Service(t *testing.T) { mercuryV1 := loop.NewMercuryV1Service(lggr, loop.GRPCOpts{}, func() *exec.Cmd { return NewHelperProcessCommand(loop.PluginMercuryName, true, 0) }, mercurytest.MercuryProvider(lggr), mercuryv1test.DataSource) - hook := mercuryV1.PluginService.XXXTestHook() + hook := mercuryV1.XXXTestHook() servicetest.Run(t, mercuryV1) t.Run("control", func(t *testing.T) { @@ -171,7 +171,7 @@ func TestMercuryV2Service(t *testing.T) { mercuryV2 := loop.NewMercuryV2Service(lggr, loop.GRPCOpts{}, func() *exec.Cmd { return NewHelperProcessCommand(loop.PluginMercuryName, true, 0) }, mercurytest.MercuryProvider(lggr), mercuryv2test.DataSource) - hook := mercuryV2.PluginService.XXXTestHook() + hook := mercuryV2.XXXTestHook() servicetest.Run(t, mercuryV2) t.Run("control", func(t *testing.T) { diff --git a/pkg/monitoring/exporter_kafka_test.go b/pkg/monitoring/exporter_kafka_test.go index 8081aaa718..6aa77dfbb2 100644 --- a/pkg/monitoring/exporter_kafka_test.go +++ b/pkg/monitoring/exporter_kafka_test.go @@ -47,11 +47,12 @@ func TestKafkaExporter(t *testing.T) { for i := 0; i < 2; i++ { select { case message := <-producer.sendCh: - if message.topic == cfg.Kafka.TransmissionTopic { + switch message.topic { + case cfg.Kafka.TransmissionTopic: receivedTransmission = message - } else if message.topic == cfg.Kafka.ConfigSetSimplifiedTopic { + case cfg.Kafka.ConfigSetSimplifiedTopic: receivedConfigSetSimplified = message - } else { + default: t.Fatalf("received unexpected message with topic %s", message.topic) } case <-ctx.Done(): diff --git a/pkg/services/orgresolver/linking_test.go b/pkg/services/orgresolver/linking_test.go index f1c2b3efb0..454f62fdf7 100644 --- a/pkg/services/orgresolver/linking_test.go +++ b/pkg/services/orgresolver/linking_test.go @@ -38,7 +38,6 @@ func (m *mockJWTGenerator) CreateJWTForRequest(req any) (string, error) { // mockLinkingClientWithAuthCheck implements the LinkingServiceClient interface and checks for authorization header type mockLinkingClientWithAuthCheck struct { - expectedAuthHeader string receivedAuthHeader string } diff --git a/pkg/services/service.go b/pkg/services/service.go index fc1dfc31b8..6257ff6b51 100644 --- a/pkg/services/service.go +++ b/pkg/services/service.go @@ -67,7 +67,7 @@ type Engine struct { // }) func (e *Engine) Go(fn func(context.Context)) { e.wg.Go(func() { - ctx, cancel := e.StopChan.NewCtx() + ctx, cancel := e.NewCtx() defer cancel() fn(ctx) }) @@ -77,7 +77,7 @@ func (e *Engine) Go(fn func(context.Context)) { // Use context.WithoutCancel if the function should continue running. func (e *Engine) GoCtx(ctx context.Context, fn func(context.Context)) { e.wg.Go(func() { - ctx, cancel := e.StopChan.Ctx(ctx) + ctx, cancel := e.Ctx(ctx) defer cancel() fn(ctx) }) @@ -249,7 +249,7 @@ func (s *service) HealthReport() map[string]error { return m } -func (s *service) Name() string { return s.eng.SugaredLogger.Name() } +func (s *service) Name() string { return s.eng.Name() } func (s *service) Start(ctx context.Context) error { return s.StartOnce(s.cfg.Name, func() error { @@ -299,7 +299,7 @@ func (s *service) Close() error { }) } -func (s *service) emitHealthErr(err error) { s.StateMachine.SvcErrBuffer.Append(err) } +func (s *service) emitHealthErr(err error) { s.SvcErrBuffer.Append(err) } func (s *service) ifStarted(fn func() error) (err error) { if !s.IfStarted(func() { err = fn() }) { diff --git a/pkg/settings/limits/bound.go b/pkg/settings/limits/bound.go index 675917adcf..90e1bcfaa3 100644 --- a/pkg/settings/limits/bound.go +++ b/pkg/settings/limits/bound.go @@ -69,7 +69,7 @@ func newBoundLimiter[N Number](f Factory, bound settings.SettingSpec[N], isLower scope: bound.GetScope(), isLowerBound: isLowerBound, } - b.updater.recordLimit = func(ctx context.Context, n N) { b.recordBound(ctx, n) } + b.recordLimit = func(ctx context.Context, n N) { b.recordBound(ctx, n) } if f.Meter != nil { if b.key == "" { diff --git a/pkg/settings/limits/gate.go b/pkg/settings/limits/gate.go index 3228f1ee8d..1f368262cb 100644 --- a/pkg/settings/limits/gate.go +++ b/pkg/settings/limits/gate.go @@ -52,7 +52,7 @@ func newGateLimiter(f Factory, limit settings.SettingSpec[bool]) (GateLimiter, e key: limit.GetKey(), scope: limit.GetScope(), } - g.updater.recordLimit = func(ctx context.Context, b bool) { g.recordStatus(ctx, b) } + g.recordLimit = func(ctx context.Context, b bool) { g.recordStatus(ctx, b) } if f.Meter != nil { if g.key == "" { diff --git a/pkg/settings/limits/metrics_test.go b/pkg/settings/limits/metrics_test.go index 34ff7afcaa..29924103d8 100644 --- a/pkg/settings/limits/metrics_test.go +++ b/pkg/settings/limits/metrics_test.go @@ -34,7 +34,7 @@ func newMetricsChecker(t *testing.T) *metricsChecker { } func (mc *metricsChecker) lastResourceFirstScopeMetric(t *testing.T) metrics { - require.NoError(t, mc.MeterProvider.ForceFlush(t.Context())) + require.NoError(t, mc.ForceFlush(t.Context())) return mc.exp.lastResourceFirstScopeMetric(t) } diff --git a/pkg/settings/limits/range.go b/pkg/settings/limits/range.go index f3ee21dc20..2509c0fb23 100644 --- a/pkg/settings/limits/range.go +++ b/pkg/settings/limits/range.go @@ -57,7 +57,7 @@ func newRangeLimiter[N Number](f Factory, bound settings.SettingSpec[settings.Ra key: bound.GetKey(), scope: bound.GetScope(), } - b.updater.recordLimit = func(ctx context.Context, n settings.Range[N]) { b.recordBound(ctx, n) } + b.recordLimit = func(ctx context.Context, n settings.Range[N]) { b.recordBound(ctx, n) } if f.Meter != nil { if b.key == "" { diff --git a/pkg/settings/limits/rate.go b/pkg/settings/limits/rate.go index 4fc14bc813..04afca5f44 100644 --- a/pkg/settings/limits/rate.go +++ b/pkg/settings/limits/rate.go @@ -132,7 +132,7 @@ func newRateLimiter(scope settings.Scope, limit rate.Limit, burst int) RateLimit addUsage: func(ctx context.Context, incr int64) {}, recordDenied: func(ctx context.Context, incr int) {}, } - close(rl.updater.done) // no background routine + close(rl.done) // no background routine return rl } return &scopedRateLimiter{ diff --git a/pkg/settings/limits/resource.go b/pkg/settings/limits/resource.go index abc0c03d8e..00d40e3a2e 100644 --- a/pkg/settings/limits/resource.go +++ b/pkg/settings/limits/resource.go @@ -90,7 +90,7 @@ type resourcePoolLimiter[N Number] struct { } func (l *resourcePoolLimiter[N]) setOnLimitUpdate(fn func(ctx context.Context)) { - l.updater.onLimitUpdate = fn + l.onLimitUpdate = fn } func (l *resourcePoolLimiter[N]) createGauges(meter metric.Meter, unit string) error { @@ -169,10 +169,8 @@ type resourcePoolUsage[N Number] struct { recordAmount func(context.Context, N) recordDenied func(context.Context, N) - stopOnce sync.Once - stopCh services.StopChan - done chan struct{} - cancelSub func() // optional + stopCh services.StopChan + done chan struct{} } // onLimitUpdate is invoked when the configured limit changes. It attempts to @@ -216,7 +214,7 @@ func (l *resourcePoolLimiter[N]) newLimitUsage(opts ...metric.RecordOption) *res } // copy but replace updater u.resourcePoolLimiter = *l - u.resourcePoolLimiter.updater = newUpdater(l.lggr, l.getLimitFn, l.subFn) + u.updater = newUpdater(l.lggr, l.getLimitFn, l.subFn) return &u } @@ -381,7 +379,7 @@ func newUnscopedResourcePoolLimiter[N Number](defaultLimit N) *unscopedResourceP } l.resourcePoolUsage = l.newLimitUsage() l.setOnLimitUpdate(func(context.Context) { - l.resourcePoolUsage.onLimitUpdate() + l.onLimitUpdate() }) return l } diff --git a/pkg/settings/limits/resource_test.go b/pkg/settings/limits/resource_test.go index 5271068864..572120b062 100644 --- a/pkg/settings/limits/resource_test.go +++ b/pkg/settings/limits/resource_test.go @@ -325,7 +325,7 @@ func TestResourcePoolLimiter_WaitOrderPreserved(t *testing.T) { // Channel to signal when each waiter has been enqueued enqueued := make(chan struct{}, numWaiters) - limiter.resourcePoolUsage.setOnEnqueue(func() { + limiter.setOnEnqueue(func() { enqueued <- struct{}{} }) @@ -380,7 +380,7 @@ func TestResourcePoolLimiter_ContextCancellation(t *testing.T) { // Channel to signal when each waiter has been enqueued enqueued := make(chan struct{}, 5) - limiter.resourcePoolUsage.setOnEnqueue(func() { + limiter.setOnEnqueue(func() { enqueued <- struct{}{} }) @@ -503,7 +503,7 @@ func TestResourcePoolLimiter_LimitFlapToZeroDoesNotDeadlock(t *testing.T) { require.NoError(t, err) enqueued := make(chan struct{}, 1) - limiter.resourcePoolUsage.setOnEnqueue(func() { enqueued <- struct{}{} }) + limiter.setOnEnqueue(func() { enqueued <- struct{}{} }) waitErr := make(chan error, 1) go func() { diff --git a/pkg/settings/limits/time.go b/pkg/settings/limits/time.go index cc6b820dcd..1e15b82413 100644 --- a/pkg/settings/limits/time.go +++ b/pkg/settings/limits/time.go @@ -58,7 +58,7 @@ func (f Factory) newTimeLimiter(timeout settings.Setting[time.Duration]) (TimeLi defaultTimeout: timeout.DefaultValue, scope: timeout.Scope, } - l.updater.recordLimit = l.recordTimeout + l.recordLimit = l.recordTimeout if f.Logger != nil { l.lggr = logger.Sugared(f.Logger).Named("TimeLimiter").With("key", timeout.Key) diff --git a/pkg/settings/limits/time_test.go b/pkg/settings/limits/time_test.go index e3dfe11876..dde6ba1ce1 100644 --- a/pkg/settings/limits/time_test.go +++ b/pkg/settings/limits/time_test.go @@ -63,13 +63,13 @@ func TestFactory_NewTimeLimiter(t *testing.T) { ctx = contexts.WithCRE(ctx, tt.cre) func(ctx context.Context) { - ctx, done, err := tl.WithTimeout(ctx) + _, done, err := tl.WithTimeout(ctx) require.NoError(t, err) defer done() time.Sleep(10 * time.Millisecond) }(ctx) func(ctx context.Context) { - ctx, done, err := tl.WithTimeout(ctx) + _, done, err := tl.WithTimeout(ctx) require.NoError(t, err) defer done() time.Sleep(2 * time.Second) diff --git a/pkg/storage/workflow_client.go b/pkg/storage/workflow_client.go index 6b3d59168d..16d844921f 100644 --- a/pkg/storage/workflow_client.go +++ b/pkg/storage/workflow_client.go @@ -66,7 +66,6 @@ func (wc *workflowClient) Close() error { } type workflowConfig struct { - log logger.Logger transportCredentials credentials.TransportCredentials tlsCert string serverName string diff --git a/pkg/types/automation/basetypes.go b/pkg/types/automation/basetypes.go index da69737ab9..d172c438a9 100644 --- a/pkg/types/automation/basetypes.go +++ b/pkg/types/automation/basetypes.go @@ -30,9 +30,9 @@ var checkResultStringTemplate = `{ }` func init() { - checkResultStringTemplate = strings.Replace(checkResultStringTemplate, " ", "", -1) - checkResultStringTemplate = strings.Replace(checkResultStringTemplate, "\t", "", -1) - checkResultStringTemplate = strings.Replace(checkResultStringTemplate, "\n", "", -1) + checkResultStringTemplate = strings.ReplaceAll(checkResultStringTemplate, " ", "") + checkResultStringTemplate = strings.ReplaceAll(checkResultStringTemplate, "\t", "") + checkResultStringTemplate = strings.ReplaceAll(checkResultStringTemplate, "\n", "") } type TransmitEventType int diff --git a/pkg/types/ccipocr3/common_types.go b/pkg/types/ccipocr3/common_types.go index b64d7e51f4..357efb8380 100644 --- a/pkg/types/ccipocr3/common_types.go +++ b/pkg/types/ccipocr3/common_types.go @@ -214,5 +214,5 @@ func (b BigInt) IsEmpty() bool { } func (b BigInt) IsPositive() bool { - return b.Int != nil && b.Int.Sign() > 0 + return b.Int != nil && b.Sign() > 0 } diff --git a/pkg/types/ccipocr3/generic_types.go b/pkg/types/ccipocr3/generic_types.go index 40abe2929d..136a30131b 100644 --- a/pkg/types/ccipocr3/generic_types.go +++ b/pkg/types/ccipocr3/generic_types.go @@ -67,7 +67,7 @@ func (a TokenInfo) Validate() error { return fmt.Errorf("aggregatorAddress must be a valid ethereum address, got %d bytes expected 20", len(decoded)) } - if a.DeviationPPB.Int.Cmp(big.NewInt(0)) <= 0 { + if a.DeviationPPB.Cmp(big.NewInt(0)) <= 0 { return errors.New("deviationPPB not set or negative, must be positive") } diff --git a/pkg/types/ccipocr3/generic_types_test.go b/pkg/types/ccipocr3/generic_types_test.go index e8b759b99e..9b80588fbd 100644 --- a/pkg/types/ccipocr3/generic_types_test.go +++ b/pkg/types/ccipocr3/generic_types_test.go @@ -240,7 +240,7 @@ func TestNewTokenPrice(t *testing.T) { t.Run("base", func(t *testing.T) { tp := NewTokenPrice("link", big.NewInt(1000)) assert.Equal(t, "link", string(tp.TokenID)) - assert.Equal(t, uint64(1000), tp.Price.Int.Uint64()) + assert.Equal(t, uint64(1000), tp.Price.Uint64()) }) } diff --git a/pkg/types/mercury/v1/types.go b/pkg/types/mercury/v1/types.go index 1fc3b52ecf..b269e3a852 100644 --- a/pkg/types/mercury/v1/types.go +++ b/pkg/types/mercury/v1/types.go @@ -6,7 +6,6 @@ import ( "math/big" "github.com/smartcontractkit/libocr/offchainreporting2plus/types" - ocrtypes "github.com/smartcontractkit/libocr/offchainreporting2plus/types" "github.com/smartcontractkit/chainlink-common/pkg/types/mercury" ) @@ -67,14 +66,14 @@ type ReportCodec interface { // ParsedAttributedObservation per observer, and that all observers are // valid. However, observation values, timestamps, etc... should all be // treated as untrusted. - BuildReport(ctx context.Context, fields ReportFields) (ocrtypes.Report, error) + BuildReport(ctx context.Context, fields ReportFields) (types.Report, error) // MaxReportLength Returns the maximum length of a report based on n, the number of oracles. // The output of BuildReport must respect this maximum length. MaxReportLength(ctx context.Context, n int) (int, error) // CurrentBlockNumFromReport returns the median current block number from a report - CurrentBlockNumFromReport(context.Context, ocrtypes.Report) (int64, error) + CurrentBlockNumFromReport(context.Context, types.Report) (int64, error) } // DataSource implementations must be thread-safe. Observe may be called by many diff --git a/pkg/types/solana/contract_reader.go b/pkg/types/solana/contract_reader.go index 44919f19da..3d556d92e3 100644 --- a/pkg/types/solana/contract_reader.go +++ b/pkg/types/solana/contract_reader.go @@ -138,7 +138,7 @@ func (c *ChainContractReader) UnmarshalJSON(bytes []byte) error { return fmt.Errorf("anchorIDL field is neither a valid JSON string nor a valid IDL object: %w", err) } - if len(c.IDL.Accounts) == 0 && len(c.IDL.Events) == 0 { + if len(c.Accounts) == 0 && len(c.Events) == 0 { return fmt.Errorf("namespace idl must have at least one account or event: %w", commontypes.ErrInvalidConfig) } diff --git a/pkg/workflows/artifacts/upload_test.go b/pkg/workflows/artifacts/upload_test.go index 253b932af2..a58a048a8b 100644 --- a/pkg/workflows/artifacts/upload_test.go +++ b/pkg/workflows/artifacts/upload_test.go @@ -137,12 +137,6 @@ func (t *testArtifactStorage) getBinary(workflowID string) []byte { return t.binaries[workflowID] } -func (t *testArtifactStorage) getConfig(workflowID string) []byte { - t.mu.RLock() - defer t.mu.RUnlock() - return t.configs[workflowID] -} - // testServer runs on the given port and accepts POST multipart to: // - /artifacts//binary.wasm // - /artifacts//configs diff --git a/pkg/workflows/dontime/factory.go b/pkg/workflows/dontime/factory.go index c0e2243cfb..76c102547a 100644 --- a/pkg/workflows/dontime/factory.go +++ b/pkg/workflows/dontime/factory.go @@ -26,10 +26,8 @@ const ( var _ core.OCR3ReportingPluginFactory = &Factory{} type Factory struct { - store *Store - batchSize int - outcomePruningThreshold uint64 - lggr logger.Logger + store *Store + lggr logger.Logger services.StateMachine } diff --git a/pkg/workflows/dontime/plugin.go b/pkg/workflows/dontime/plugin.go index 4cd521c630..1e3a88935f 100644 --- a/pkg/workflows/dontime/plugin.go +++ b/pkg/workflows/dontime/plugin.go @@ -5,7 +5,6 @@ import ( "errors" "fmt" "slices" - "sync" "time" "google.golang.org/protobuf/proto" @@ -21,8 +20,6 @@ import ( ) type Plugin struct { - mu sync.RWMutex - store *Store config ocr3types.ReportingPluginConfig offChainConfig *pb.Config diff --git a/pkg/workflows/dontime/plugin_test.go b/pkg/workflows/dontime/plugin_test.go index 89c33fdcde..335353acb0 100644 --- a/pkg/workflows/dontime/plugin_test.go +++ b/pkg/workflows/dontime/plugin_test.go @@ -150,6 +150,7 @@ func TestPlugin_Outcome(t *testing.T) { require.NoError(t, err) query, err := plugin.Query(ctx, ocr3types.OutcomeContext{PreviousOutcome: []byte("")}) + require.NoError(t, err) // Add single request to queue executionID := "workflow-123" diff --git a/pkg/workflows/dontime/store.go b/pkg/workflows/dontime/store.go index 2e7f204057..78da3e162f 100644 --- a/pkg/workflows/dontime/store.go +++ b/pkg/workflows/dontime/store.go @@ -151,12 +151,3 @@ func (s *Store) deleteExecutionID(executionID string) { delete(s.donTimes, executionID) delete(s.requests, executionID) } - -func (s *Store) deleteExecutionIDs(executionIDs []string) { - s.mu.Lock() - defer s.mu.Unlock() - for _, id := range executionIDs { - delete(s.donTimes, id) - delete(s.requests, id) - } -} diff --git a/pkg/workflows/sdk/builder.go b/pkg/workflows/sdk/builder.go index efefb681b8..d782abbc4d 100644 --- a/pkg/workflows/sdk/builder.go +++ b/pkg/workflows/sdk/builder.go @@ -93,7 +93,7 @@ type singleCapList[O any] struct { } func (s singleCapList[O]) Index(i int) CapDefinition[O] { - listRef, ok := s.CapDefinition.Ref().(string) + listRef, ok := s.Ref().(string) // There are two cases to indexing: // It's a ref, in which case we just want to index the ref, i.e. ref -> ref.i diff --git a/pkg/workflows/sdk/testutils/mocks.go b/pkg/workflows/sdk/testutils/mocks.go index 8b0587702f..371d05b026 100644 --- a/pkg/workflows/sdk/testutils/mocks.go +++ b/pkg/workflows/sdk/testutils/mocks.go @@ -132,7 +132,7 @@ type TriggerMock[O any] struct { var _ capabilities.TriggerCapability = &TriggerMock[any]{} func (t *TriggerMock[O]) RegisterTrigger(ctx context.Context, request capabilities.TriggerRegistrationRequest) (<-chan capabilities.TriggerResponse, error) { - result, err := t.mockBase.fn(struct{}{}) + result, err := t.fn(struct{}{}) wrapped, wErr := values.CreateMapFromStruct(result) if wErr != nil { @@ -182,9 +182,9 @@ var _ capabilities.ExecutableCapability = &TargetMock[any]{} func (t *TargetMock[I]) GetAllWrites() TargetResults[I] { targetResults := TargetResults[I]{} - for ref := range t.mockBase.inputs { + for ref := range t.inputs { targetResults.NumRuns++ - step := t.mockBase.GetStep(ref) + step := t.GetStep(ref) targetResults.Inputs = append(targetResults.Inputs, step.Input) if step.Error != nil { targetResults.Errors = append(targetResults.Errors, step.Error) diff --git a/pkg/workflows/utils.go b/pkg/workflows/utils.go index 5004174442..86f6a070f1 100644 --- a/pkg/workflows/utils.go +++ b/pkg/workflows/utils.go @@ -141,7 +141,7 @@ func HashTruncateName(name string) string { hash := sha256.Sum256([]byte(name)) // Encode as hex to ensure UTF8 - var hashBytes []byte = hash[:] + var hashBytes = hash[:] resultHex := hex.EncodeToString(hashBytes) // Truncate to 10 bytes diff --git a/pkg/workflows/wasm/host/standard_test.go b/pkg/workflows/wasm/host/standard_test.go index fce7ae10f6..76b03c471f 100644 --- a/pkg/workflows/wasm/host/standard_test.go +++ b/pkg/workflows/wasm/host/standard_test.go @@ -174,7 +174,7 @@ func TestStandardModeSwitch(t *testing.T) { input := &basicaction.Inputs{} assert.NoError(t, request.Payload.UnmarshalTo(input)) assert.True(t, input.InputThing) - payload, err := anypb.New(&basicaction.Outputs{AdaptedThing: fmt.Sprintf("test")}) + payload, err := anypb.New(&basicaction.Outputs{AdaptedThing: "test"}) require.NoError(t, err) return &sdk.CapabilityResponse{ Response: &sdk.CapabilityResponse_Payload{Payload: payload}, @@ -553,11 +553,6 @@ func makeTestModule(t *testing.T) *module { return makeTestModuleByName(t, testName, nil) } -func makeTestModuleWithCfg(t *testing.T, cfg *ModuleConfig) *module { - testName := strcase.ToSnake(t.Name()[len("TestStandard"):]) - return makeTestModuleByName(t, testName, cfg) -} - func makeTestModuleByName(t *testing.T, testName string, cfg *ModuleConfig) *module { wasmName := path.Join(testName, "test.wasm") cmd := exec.Command("make", wasmName) // #nosec diff --git a/pkg/workflows/wasm/host/wasm_test.go b/pkg/workflows/wasm/host/wasm_test.go index 8f13638f12..38b6e6392b 100644 --- a/pkg/workflows/wasm/host/wasm_test.go +++ b/pkg/workflows/wasm/host/wasm_test.go @@ -20,7 +20,6 @@ import ( "go.uber.org/zap/zapcore" "github.com/smartcontractkit/chainlink-common/pkg/capabilities/pb" - capabilitiespb "github.com/smartcontractkit/chainlink-common/pkg/capabilities/pb" "github.com/smartcontractkit/chainlink-common/pkg/config" "github.com/smartcontractkit/chainlink-common/pkg/logger" "github.com/smartcontractkit/chainlink-common/pkg/settings/limits" @@ -184,10 +183,10 @@ func Test_Compute_Emit(t *testing.T) { Id: uuid.New().String(), Message: &wasmpb.Request_ComputeRequest{ ComputeRequest: &wasmpb.ComputeRequest{ - Request: &capabilitiespb.CapabilityRequest{ + Request: &pb.CapabilityRequest{ Inputs: &valuespb.Map{}, Config: &valuespb.Map{}, - Metadata: &capabilitiespb.RequestMetadata{ + Metadata: &pb.RequestMetadata{ ReferenceId: "transform", WorkflowId: "workflow-id", WorkflowName: "workflow-name", @@ -276,8 +275,8 @@ func Test_Compute_Emit(t *testing.T) { }, } for i := range expectedEntries { - assert.Equal(t, expectedEntries[i].Level, logs.AllUntimed()[i].Entry.Level) - assert.Equal(t, expectedEntries[i].Message, logs.AllUntimed()[i].Entry.Message) + assert.Equal(t, expectedEntries[i].Level, logs.AllUntimed()[i].Level) + assert.Equal(t, expectedEntries[i].Message, logs.AllUntimed()[i].Message) } }) @@ -300,10 +299,10 @@ func Test_Compute_Emit(t *testing.T) { Id: uuid.New().String(), Message: &wasmpb.Request_ComputeRequest{ ComputeRequest: &wasmpb.ComputeRequest{ - Request: &capabilitiespb.CapabilityRequest{ + Request: &pb.CapabilityRequest{ Inputs: &valuespb.Map{}, Config: &valuespb.Map{}, - Metadata: &capabilitiespb.RequestMetadata{ + Metadata: &pb.RequestMetadata{ ReferenceId: "transform", }, }, @@ -327,8 +326,8 @@ func Test_Compute_Emit(t *testing.T) { } for i := range expectedEntries { - assert.Equal(t, expectedEntries[i].Log.Level, logs.AllUntimed()[i].Entry.Level) - assert.Equal(t, expectedEntries[i].Log.Message, logs.AllUntimed()[i].Entry.Message) + assert.Equal(t, expectedEntries[i].Log.Level, logs.AllUntimed()[i].Level) + assert.Equal(t, expectedEntries[i].Log.Message, logs.AllUntimed()[i].Message) } }) } @@ -350,10 +349,10 @@ func Test_Compute_PanicIsRecovered(t *testing.T) { Id: uuid.New().String(), Message: &wasmpb.Request_ComputeRequest{ ComputeRequest: &wasmpb.ComputeRequest{ - Request: &capabilitiespb.CapabilityRequest{ + Request: &pb.CapabilityRequest{ Inputs: &valuespb.Map{}, Config: &valuespb.Map{}, - Metadata: &capabilitiespb.RequestMetadata{ + Metadata: &pb.RequestMetadata{ ReferenceId: "transform", }, }, @@ -398,10 +397,10 @@ func Test_Compute_Fetch(t *testing.T) { Id: uuid.New().String(), Message: &wasmpb.Request_ComputeRequest{ ComputeRequest: &wasmpb.ComputeRequest{ - Request: &capabilitiespb.CapabilityRequest{ + Request: &pb.CapabilityRequest{ Inputs: &valuespb.Map{}, Config: &valuespb.Map{}, - Metadata: &capabilitiespb.RequestMetadata{ + Metadata: &pb.RequestMetadata{ ReferenceId: "transform", }, }, @@ -451,10 +450,10 @@ func Test_Compute_Fetch(t *testing.T) { Id: uuid.New().String(), Message: &wasmpb.Request_ComputeRequest{ ComputeRequest: &wasmpb.ComputeRequest{ - Request: &capabilitiespb.CapabilityRequest{ + Request: &pb.CapabilityRequest{ Inputs: &valuespb.Map{}, Config: &valuespb.Map{}, - Metadata: &capabilitiespb.RequestMetadata{ + Metadata: &pb.RequestMetadata{ ReferenceId: "transform", }, }, @@ -502,10 +501,10 @@ func Test_Compute_Fetch(t *testing.T) { Id: uuid.New().String(), Message: &wasmpb.Request_ComputeRequest{ ComputeRequest: &wasmpb.ComputeRequest{ - Request: &capabilitiespb.CapabilityRequest{ + Request: &pb.CapabilityRequest{ Inputs: &valuespb.Map{}, Config: &valuespb.Map{}, - Metadata: &capabilitiespb.RequestMetadata{ + Metadata: &pb.RequestMetadata{ ReferenceId: "transform", }, }, @@ -547,10 +546,10 @@ func Test_Compute_Fetch(t *testing.T) { Id: uuid.New().String(), Message: &wasmpb.Request_ComputeRequest{ ComputeRequest: &wasmpb.ComputeRequest{ - Request: &capabilitiespb.CapabilityRequest{ + Request: &pb.CapabilityRequest{ Inputs: &valuespb.Map{}, Config: &valuespb.Map{}, - Metadata: &capabilitiespb.RequestMetadata{ + Metadata: &pb.RequestMetadata{ ReferenceId: "transform", }, }, @@ -568,8 +567,8 @@ func Test_Compute_Fetch(t *testing.T) { }, } for i := range expectedEntries { - assert.Equal(t, expectedEntries[i].Log.Level, logs.AllUntimed()[i].Entry.Level) - assert.Equal(t, expectedEntries[i].Log.Message, logs.AllUntimed()[i].Entry.Message) + assert.Equal(t, expectedEntries[i].Log.Level, logs.AllUntimed()[i].Level) + assert.Equal(t, expectedEntries[i].Log.Message, logs.AllUntimed()[i].Message) } }) @@ -577,7 +576,7 @@ func Test_Compute_Fetch(t *testing.T) { t.Parallel() type testkey string var key testkey = "test-key" - var expectedValue string = "test-value" + var expectedValue = "test-value" expected := FetchResponse{ ExecutionError: false, @@ -605,10 +604,10 @@ func Test_Compute_Fetch(t *testing.T) { Id: uuid.New().String(), Message: &wasmpb.Request_ComputeRequest{ ComputeRequest: &wasmpb.ComputeRequest{ - Request: &capabilitiespb.CapabilityRequest{ + Request: &pb.CapabilityRequest{ Inputs: &valuespb.Map{}, Config: &valuespb.Map{}, - Metadata: &capabilitiespb.RequestMetadata{ + Metadata: &pb.RequestMetadata{ ReferenceId: "transform", }, }, @@ -654,10 +653,10 @@ func Test_Compute_Fetch(t *testing.T) { Id: uuid.New().String(), Message: &wasmpb.Request_ComputeRequest{ ComputeRequest: &wasmpb.ComputeRequest{ - Request: &capabilitiespb.CapabilityRequest{ + Request: &pb.CapabilityRequest{ Inputs: &valuespb.Map{}, Config: &valuespb.Map{}, - Metadata: &capabilitiespb.RequestMetadata{ + Metadata: &pb.RequestMetadata{ ReferenceId: "transform", }, }, @@ -706,10 +705,10 @@ func Test_Compute_Fetch(t *testing.T) { Id: uuid.New().String(), Message: &wasmpb.Request_ComputeRequest{ ComputeRequest: &wasmpb.ComputeRequest{ - Request: &capabilitiespb.CapabilityRequest{ + Request: &pb.CapabilityRequest{ Inputs: &valuespb.Map{}, Config: &valuespb.Map{}, - Metadata: &capabilitiespb.RequestMetadata{ + Metadata: &pb.RequestMetadata{ ReferenceId: "transform", }, }, @@ -750,10 +749,10 @@ func Test_Compute_Fetch(t *testing.T) { Id: uuid.New().String(), Message: &wasmpb.Request_ComputeRequest{ ComputeRequest: &wasmpb.ComputeRequest{ - Request: &capabilitiespb.CapabilityRequest{ + Request: &pb.CapabilityRequest{ Inputs: &valuespb.Map{}, Config: &valuespb.Map{}, - Metadata: &capabilitiespb.RequestMetadata{ + Metadata: &pb.RequestMetadata{ ReferenceId: "transform", }, }, @@ -795,10 +794,10 @@ func Test_Compute_Fetch(t *testing.T) { Id: uuid.New().String(), Message: &wasmpb.Request_ComputeRequest{ ComputeRequest: &wasmpb.ComputeRequest{ - Request: &capabilitiespb.CapabilityRequest{ + Request: &pb.CapabilityRequest{ Inputs: &valuespb.Map{}, Config: &valuespb.Map{}, - Metadata: &capabilitiespb.RequestMetadata{ + Metadata: &pb.RequestMetadata{ ReferenceId: "transform", }, }, @@ -840,10 +839,10 @@ func Test_Compute_Fetch(t *testing.T) { Id: uuid.New().String(), Message: &wasmpb.Request_ComputeRequest{ ComputeRequest: &wasmpb.ComputeRequest{ - Request: &capabilitiespb.CapabilityRequest{ + Request: &pb.CapabilityRequest{ Inputs: &valuespb.Map{}, Config: &valuespb.Map{}, - Metadata: &capabilitiespb.RequestMetadata{ + Metadata: &pb.RequestMetadata{ ReferenceId: "transform", }, }, @@ -896,8 +895,8 @@ func TestModule_Errors(t *testing.T) { Id: uuid.New().String(), Message: &wasmpb.Request_ComputeRequest{ ComputeRequest: &wasmpb.ComputeRequest{ - Request: &capabilitiespb.CapabilityRequest{ - Metadata: &capabilitiespb.RequestMetadata{ + Request: &pb.CapabilityRequest{ + Metadata: &pb.RequestMetadata{ ReferenceId: "doesnt-exist", }, }, @@ -1053,10 +1052,10 @@ func TestModule_Sandbox_CantReadFiles(t *testing.T) { Id: uuid.New().String(), Message: &wasmpb.Request_ComputeRequest{ ComputeRequest: &wasmpb.ComputeRequest{ - Request: &capabilitiespb.CapabilityRequest{ + Request: &pb.CapabilityRequest{ Inputs: &valuespb.Map{}, Config: &valuespb.Map{}, - Metadata: &capabilitiespb.RequestMetadata{ + Metadata: &pb.RequestMetadata{ ReferenceId: "transform", }, }, @@ -1081,10 +1080,10 @@ func TestModule_Sandbox_CantCreateDir(t *testing.T) { Id: uuid.New().String(), Message: &wasmpb.Request_ComputeRequest{ ComputeRequest: &wasmpb.ComputeRequest{ - Request: &capabilitiespb.CapabilityRequest{ + Request: &pb.CapabilityRequest{ Inputs: &valuespb.Map{}, Config: &valuespb.Map{}, - Metadata: &capabilitiespb.RequestMetadata{ + Metadata: &pb.RequestMetadata{ ReferenceId: "transform", }, }, @@ -1109,10 +1108,10 @@ func TestModule_Sandbox_HTTPRequest(t *testing.T) { Id: uuid.New().String(), Message: &wasmpb.Request_ComputeRequest{ ComputeRequest: &wasmpb.ComputeRequest{ - Request: &capabilitiespb.CapabilityRequest{ + Request: &pb.CapabilityRequest{ Inputs: &valuespb.Map{}, Config: &valuespb.Map{}, - Metadata: &capabilitiespb.RequestMetadata{ + Metadata: &pb.RequestMetadata{ ReferenceId: "transform", }, }, @@ -1124,7 +1123,6 @@ func TestModule_Sandbox_HTTPRequest(t *testing.T) { } func TestModule_Sandbox_ReadEnv(t *testing.T) { - t.Parallel() ctx := t.Context() binary := createTestBinary(envBinaryCmd, envBinaryLocation, true, t) @@ -1133,17 +1131,16 @@ func TestModule_Sandbox_ReadEnv(t *testing.T) { m.Start() - os.Setenv("FOO", "BAR") - defer os.Unsetenv("FOO") + t.Setenv("FOO", "BAR") req := &wasmpb.Request{ Id: uuid.New().String(), Message: &wasmpb.Request_ComputeRequest{ ComputeRequest: &wasmpb.ComputeRequest{ - Request: &capabilitiespb.CapabilityRequest{ + Request: &pb.CapabilityRequest{ Inputs: &valuespb.Map{}, Config: &valuespb.Map{}, - Metadata: &capabilitiespb.RequestMetadata{ + Metadata: &pb.RequestMetadata{ ReferenceId: "transform", }, }, @@ -1161,10 +1158,10 @@ func TestModule_Sandbox_RandomGet(t *testing.T) { Id: uuid.New().String(), Message: &wasmpb.Request_ComputeRequest{ ComputeRequest: &wasmpb.ComputeRequest{ - Request: &capabilitiespb.CapabilityRequest{ + Request: &pb.CapabilityRequest{ Inputs: &valuespb.Map{}, Config: &valuespb.Map{}, - Metadata: &capabilitiespb.RequestMetadata{ + Metadata: &pb.RequestMetadata{ ReferenceId: "transform", }, }, @@ -1231,10 +1228,10 @@ func TestModule_MaxResponseSizeBytesLimit(t *testing.T) { Id: uuid.New().String(), Message: &wasmpb.Request_ComputeRequest{ ComputeRequest: &wasmpb.ComputeRequest{ - Request: &capabilitiespb.CapabilityRequest{ + Request: &pb.CapabilityRequest{ Inputs: &valuespb.Map{}, Config: &valuespb.Map{}, - Metadata: &capabilitiespb.RequestMetadata{ + Metadata: &pb.RequestMetadata{ ReferenceId: "transform", }, }, @@ -1265,10 +1262,10 @@ func TestModule_MaxResponseSizeBytesLimit(t *testing.T) { Id: uuid.New().String(), Message: &wasmpb.Request_ComputeRequest{ ComputeRequest: &wasmpb.ComputeRequest{ - Request: &capabilitiespb.CapabilityRequest{ + Request: &pb.CapabilityRequest{ Inputs: &valuespb.Map{}, Config: &valuespb.Map{}, - Metadata: &capabilitiespb.RequestMetadata{ + Metadata: &pb.RequestMetadata{ ReferenceId: "transform", }, }, @@ -1301,10 +1298,10 @@ func TestModule_MaxResponseSizeBytesLimit(t *testing.T) { Id: uuid.New().String(), Message: &wasmpb.Request_ComputeRequest{ ComputeRequest: &wasmpb.ComputeRequest{ - Request: &capabilitiespb.CapabilityRequest{ + Request: &pb.CapabilityRequest{ Inputs: &valuespb.Map{}, Config: &valuespb.Map{}, - Metadata: &capabilitiespb.RequestMetadata{ + Metadata: &pb.RequestMetadata{ ReferenceId: "transform", WorkflowId: "workflow-id", WorkflowName: "workflow-name", @@ -1331,8 +1328,8 @@ func TestModule_MaxResponseSizeBytesLimit(t *testing.T) { }, } for i := range expectedEntries { - assert.Equal(t, expectedEntries[i].Level, logs.AllUntimed()[i].Entry.Level) - assert.Equal(t, expectedEntries[i].Message, logs.AllUntimed()[i].Entry.Message) + assert.Equal(t, expectedEntries[i].Level, logs.AllUntimed()[i].Level) + assert.Equal(t, expectedEntries[i].Message, logs.AllUntimed()[i].Message) } }) t.Run("Emitted message size outside the limit", func(t *testing.T) { @@ -1355,10 +1352,10 @@ func TestModule_MaxResponseSizeBytesLimit(t *testing.T) { Id: uuid.New().String(), Message: &wasmpb.Request_ComputeRequest{ ComputeRequest: &wasmpb.ComputeRequest{ - Request: &capabilitiespb.CapabilityRequest{ + Request: &pb.CapabilityRequest{ Inputs: &valuespb.Map{}, Config: &valuespb.Map{}, - Metadata: &capabilitiespb.RequestMetadata{ + Metadata: &pb.RequestMetadata{ ReferenceId: "transform", WorkflowId: "workflow-id", WorkflowName: "workflow-name", @@ -1386,8 +1383,8 @@ func TestModule_MaxResponseSizeBytesLimit(t *testing.T) { }, } for i := range expectedEntries { - assert.Equal(t, expectedEntries[i].Level, logs.AllUntimed()[i].Entry.Level) - assert.Equal(t, expectedEntries[i].Message, logs.AllUntimed()[i].Entry.Message) + assert.Equal(t, expectedEntries[i].Level, logs.AllUntimed()[i].Level) + assert.Equal(t, expectedEntries[i].Message, logs.AllUntimed()[i].Message) } }) } diff --git a/pkg/workflows/wasm/runner.go b/pkg/workflows/wasm/runner.go index 6eb5c6a9b1..7319b0b1f0 100644 --- a/pkg/workflows/wasm/runner.go +++ b/pkg/workflows/wasm/runner.go @@ -100,7 +100,6 @@ func (r *Runner) ExitWithError(err error) { } r.sendResponse(errorResponse(r.req.Id, err)) - return } func errorResponse(id string, err error) *wasmpb.Response {