From 0ded7bcd623cd8bc2828a95ff49ddc7fcb776e74 Mon Sep 17 00:00:00 2001 From: Rob Mulholand Date: Fri, 18 Oct 2019 10:20:53 -0500 Subject: [PATCH 1/4] Prefer fmt.Errorf(s) to errors.New(fmt.Sprintf(s)) --- pkg/config/plugin.go | 2 +- pkg/datastore/postgres/errors.go | 3 +-- pkg/plugin/builder/builder.go | 5 ++--- pkg/plugin/manager/manager.go | 13 ++++++------- pkg/plugin/writer/writer.go | 5 ++--- 5 files changed, 12 insertions(+), 16 deletions(-) diff --git a/pkg/config/plugin.go b/pkg/config/plugin.go index fad07cbc..92461fba 100644 --- a/pkg/config/plugin.go +++ b/pkg/config/plugin.go @@ -71,7 +71,7 @@ func (pluginConfig *Plugin) GetMigrationsPaths() ([]string, error) { if ok { conflictingPath := paths[transformer.MigrationRank] if conflictingPath != cleanPath { - return nil, errors.New(fmt.Sprintf("transformer %s has the same migration rank (%d) as another transformer", name, transformer.MigrationRank)) + return nil, fmt.Errorf("transformer %s has the same migration rank (%d) as another transformer", name, transformer.MigrationRank) } } paths[transformer.MigrationRank] = cleanPath diff --git a/pkg/datastore/postgres/errors.go b/pkg/datastore/postgres/errors.go index ffb23e78..eac04b8c 100644 --- a/pkg/datastore/postgres/errors.go +++ b/pkg/datastore/postgres/errors.go @@ -1,7 +1,6 @@ package postgres import ( - "errors" "fmt" ) @@ -34,5 +33,5 @@ func ErrUnableToSetNode(setErr error) error { } func formatError(msg, err string) error { - return errors.New(fmt.Sprintf("%s: %s", msg, err)) + return fmt.Errorf("%s: %s", msg, err) } diff --git a/pkg/plugin/builder/builder.go b/pkg/plugin/builder/builder.go index f126a9dc..d6de5ba5 100644 --- a/pkg/plugin/builder/builder.go +++ b/pkg/plugin/builder/builder.go @@ -17,7 +17,6 @@ package builder import ( - "errors" "fmt" "os" "os/exec" @@ -68,7 +67,7 @@ func (b *builder) BuildPlugin() error { // Build the .go file into a .so plugin execErr := exec.Command("go", "build", "-buildmode=plugin", "-o", soFile, b.goFile).Run() if execErr != nil { - return errors.New(fmt.Sprintf("unable to build .so file: %s", execErr.Error())) + return fmt.Errorf("unable to build .so file: %s", execErr.Error()) } return nil } @@ -94,7 +93,7 @@ func (b *builder) setupBuildEnv() error { copyErr := helpers.CopyDir(src, dst, "vendor") if copyErr != nil { - return errors.New(fmt.Sprintf("unable to copy transformer dependency from %s to %s: %v", src, dst, copyErr)) + return fmt.Errorf("unable to copy transformer dependency from %s to %s: %v", src, dst, copyErr) } // Have to clear out the copied over vendor lib or plugin won't build (see issue above) diff --git a/pkg/plugin/manager/manager.go b/pkg/plugin/manager/manager.go index 0b526b6e..0b96c764 100644 --- a/pkg/plugin/manager/manager.go +++ b/pkg/plugin/manager/manager.go @@ -18,7 +18,6 @@ package manager import ( "database/sql" - "errors" "fmt" "github.com/lib/pq" "github.com/pressly/goose" @@ -59,7 +58,7 @@ func (m *manager) setDB() error { } dbConnector, err := pq.NewConnector(pgStr) if err != nil { - return errors.New(fmt.Sprintf("can't connect to db: %s", err.Error())) + return fmt.Errorf("can't connect to db: %s", err.Error()) } m.db = sql.OpenDB(dbConnector) return nil @@ -99,12 +98,12 @@ func (m *manager) setupMigrationEnv() error { removeErr := os.RemoveAll(m.tmpMigDir) if removeErr != nil { removeErrString := "unable to remove file found at %s where tmp directory needs to be written: %s" - return errors.New(fmt.Sprintf(removeErrString, m.tmpMigDir, removeErr.Error())) + return fmt.Errorf(removeErrString, m.tmpMigDir, removeErr.Error()) } mkdirErr := os.Mkdir(m.tmpMigDir, os.FileMode(os.ModePerm)) if mkdirErr != nil { mkdirErrString := "unable to create temporary migration directory %s: %s" - return errors.New(fmt.Sprintf(mkdirErrString, m.tmpMigDir, mkdirErr.Error())) + return fmt.Errorf(mkdirErrString, m.tmpMigDir, mkdirErr.Error()) } return nil @@ -145,18 +144,18 @@ func (m *manager) fixAndRun(path string) error { if m.db == nil { setErr := m.setDB() if setErr != nil { - return errors.New(fmt.Sprintf("could not open db: %s", setErr.Error())) + return fmt.Errorf("could not open db: %s", setErr.Error()) } } // Fix the migrations fixErr := goose.Fix(m.tmpMigDir) if fixErr != nil { - return errors.New(fmt.Sprintf("version fixing for plugin migrations at %s failed: %s", path, fixErr.Error())) + return fmt.Errorf("version fixing for plugin migrations at %s failed: %s", path, fixErr.Error()) } // Run the copied migrations with goose upErr := goose.Up(m.db, m.tmpMigDir) if upErr != nil { - return errors.New(fmt.Sprintf("db migrations for plugin transformers at %s failed: %s", path, upErr.Error())) + return fmt.Errorf("db migrations for plugin transformers at %s failed: %s", path, upErr.Error()) } return nil } diff --git a/pkg/plugin/writer/writer.go b/pkg/plugin/writer/writer.go index e888bc5b..3cc1a71d 100644 --- a/pkg/plugin/writer/writer.go +++ b/pkg/plugin/writer/writer.go @@ -17,7 +17,6 @@ package writer import ( - "errors" "fmt" . "github.com/dave/jennifer/jen" @@ -89,7 +88,7 @@ func (w *writer) WritePlugin() error { // Write code to destination file err = f.Save(goFile) if err != nil { - return errors.New(fmt.Sprintf("failed to save generated .go file: %s\r\n%s", goFile, err.Error())) + return fmt.Errorf("failed to save generated .go file: %s\r\n%s", goFile, err.Error()) } return nil } @@ -107,7 +106,7 @@ func (w *writer) collectTransformers() (map[config.TransformerType][]Code, error case config.EthContract: code[config.EthContract] = append(code[config.EthContract], Qual(path, "ContractTransformerInitializer")) default: - return nil, errors.New(fmt.Sprintf("invalid transformer type %s", transformer.Type)) + return nil, fmt.Errorf("invalid transformer type %s", transformer.Type) } } From eba868ff0088c2d28810c0b5328327ab6dc4fda9 Mon Sep 17 00:00:00 2001 From: Rob Mulholand Date: Fri, 18 Oct 2019 10:24:33 -0500 Subject: [PATCH 2/4] Drop else when if statement includes return --- libraries/shared/logs/extractor.go | 3 +-- pkg/eth/client/rpc_client.go | 3 +-- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/libraries/shared/logs/extractor.go b/libraries/shared/logs/extractor.go index bbd769c2..11d25445 100644 --- a/libraries/shared/logs/extractor.go +++ b/libraries/shared/logs/extractor.go @@ -130,9 +130,8 @@ func logError(description string, err error, header core.Header) { func getCheckCount(recheckHeaders constants.TransformerExecution) int64 { if recheckHeaders == constants.HeaderUnchecked { return 1 - } else { - return constants.RecheckHeaderCap } + return constants.RecheckHeaderCap } func (extractor *LogExtractor) updateCheckedHeaders(config transformer.EventTransformerConfig) error { diff --git a/pkg/eth/client/rpc_client.go b/pkg/eth/client/rpc_client.go index d6f6a738..837de9ed 100644 --- a/pkg/eth/client/rpc_client.go +++ b/pkg/eth/client/rpc_client.go @@ -49,9 +49,8 @@ func (client RpcClient) CallContext(ctx context.Context, result interface{}, met //Ganache however does not ignore it, and throws an 'Incorrect number of arguments' error. if args == nil { return client.client.CallContext(ctx, result, method) - } else { - return client.client.CallContext(ctx, result, method, args...) } + return client.client.CallContext(ctx, result, method, args...) } func (client RpcClient) IpcPath() string { From e1236b4072892a44b84e834c7acf0b436e7400a5 Mon Sep 17 00:00:00 2001 From: Rob Mulholand Date: Fri, 18 Oct 2019 11:16:19 -0500 Subject: [PATCH 3/4] Prefer all caps for initialisms and acronyms --- cmd/composeAndExecute.go | 2 +- cmd/execute.go | 2 +- cmd/root.go | 10 ++-- integration_test/block_rewards_test.go | 16 +++---- integration_test/contract_test.go | 24 +++++----- integration_test/geth_blockchain_test.go | 8 ++-- .../factories/event/transformer_test.go | 4 +- .../fetcher/geth_rpc_storage_fetcher.go | 8 ++-- .../fetcher/geth_rpc_storage_fetcher_test.go | 4 +- libraries/shared/logs/extractor.go | 8 ++-- libraries/shared/logs/extractor_test.go | 4 +- libraries/shared/mocks/storage_queue.go | 4 +- .../shared/repository/address_repository.go | 14 +++--- .../repository/address_repository_test.go | 6 +-- .../shared/storage/storage_queue_test.go | 6 +-- libraries/shared/storage/utils/diff.go | 2 +- .../shared/streamer/statediff_streamer.go | 4 +- .../streamer/statediff_streamer_test.go | 2 +- libraries/shared/watcher/storage_watcher.go | 4 +- .../shared/watcher/storage_watcher_test.go | 14 +++--- .../header/repository/header_repository.go | 2 +- .../repository/header_repository_test.go | 18 +++---- .../header/transformer/transformer.go | 8 ++-- .../shared/getter/getter_test.go | 4 +- .../shared/helpers/test_helpers/database.go | 48 +++++++++---------- .../repository/event_repository_test.go | 8 ++-- .../repository/method_repository_test.go | 4 +- pkg/core/header.go | 2 +- pkg/core/rpc_client.go | 2 +- pkg/core/transaction.go | 2 +- pkg/core/uncle.go | 2 +- pkg/datastore/postgres/postgres.go | 6 +-- .../postgres/repositories/block_repository.go | 42 ++++++++-------- .../repositories/full_sync_log_repository.go | 4 +- .../full_sync_receipt_repository.go | 34 ++++++------- .../repositories/header_repository.go | 14 +++--- .../repositories/header_repository_test.go | 2 +- .../header_sync_log_repository.go | 2 +- .../header_sync_log_repository_test.go | 4 +- .../header_sync_receipt_repository.go | 12 ++--- pkg/datastore/repository.go | 8 ++-- pkg/eth/abi.go | 4 +- pkg/eth/blockchain.go | 8 ++-- pkg/eth/blockchain_test.go | 4 +- pkg/eth/client/rpc_client.go | 16 +++---- pkg/eth/cold_import/importer.go | 12 ++--- pkg/eth/cold_import/node_builder.go | 8 ++-- pkg/eth/cold_import/node_builder_test.go | 2 +- .../cold_db/transaction_converter.go | 2 +- .../converters/common/block_converter_test.go | 18 +++---- .../common/transaction_converter.go | 2 +- .../converters/rpc/transaction_converter.go | 16 +++---- .../rpc/transaction_converter_test.go | 20 ++++---- pkg/eth/node/node.go | 22 ++++----- pkg/eth/node/node_test.go | 12 ++--- pkg/fakes/mock_block_repository.go | 12 ++--- pkg/fakes/mock_blockchain.go | 38 +++++++-------- pkg/fakes/mock_parser.go | 4 +- pkg/fakes/mock_receipt_repository.go | 14 +++--- pkg/fakes/mock_rpc_client.go | 34 ++++++------- pkg/fakes/mock_transaction_converter.go | 2 +- test_config/test_config.go | 6 +-- 62 files changed, 315 insertions(+), 315 deletions(-) diff --git a/cmd/composeAndExecute.go b/cmd/composeAndExecute.go index eea5e686..cb244e17 100644 --- a/cmd/composeAndExecute.go +++ b/cmd/composeAndExecute.go @@ -187,7 +187,7 @@ func composeAndExecute() { rpcClient, _ := getClients() stateDiffStreamer := streamer.NewStateDiffStreamer(rpcClient) payloadChan := make(chan statediff.Payload) - storageFetcher := fetcher.NewGethRpcStorageFetcher(&stateDiffStreamer, payloadChan) + storageFetcher := fetcher.NewGethRPCStorageFetcher(&stateDiffStreamer, payloadChan) sw := watcher.NewStorageWatcher(storageFetcher, &db) sw.AddTransformers(ethStorageInitializers) wg.Add(1) diff --git a/cmd/execute.go b/cmd/execute.go index d04bc205..c68b7e08 100644 --- a/cmd/execute.go +++ b/cmd/execute.go @@ -131,7 +131,7 @@ func execute() { rpcClient, _ := getClients() stateDiffStreamer := streamer.NewStateDiffStreamer(rpcClient) payloadChan := make(chan statediff.Payload) - storageFetcher := fetcher.NewGethRpcStorageFetcher(&stateDiffStreamer, payloadChan) + storageFetcher := fetcher.NewGethRPCStorageFetcher(&stateDiffStreamer, payloadChan) sw := watcher.NewStorageWatcher(storageFetcher, &db) sw.AddTransformers(ethStorageInitializers) wg.Add(1) diff --git a/cmd/root.go b/cmd/root.go index fb6a1375..cd8e4fd1 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -159,18 +159,18 @@ func getBlockChain() *eth.BlockChain { rpcClient, ethClient := getClients() vdbEthClient := client.NewEthClient(ethClient) vdbNode := node.MakeNode(rpcClient) - transactionConverter := vRpc.NewRpcTransactionConverter(ethClient) + transactionConverter := vRpc.NewRPCTransactionConverter(ethClient) return eth.NewBlockChain(vdbEthClient, rpcClient, vdbNode, transactionConverter) } -func getClients() (client.RpcClient, *ethclient.Client) { - rawRpcClient, err := rpc.Dial(ipc) +func getClients() (client.RPCClient, *ethclient.Client) { + rawRPCClient, err := rpc.Dial(ipc) if err != nil { LogWithCommand.Fatal(err) } - rpcClient := client.NewRpcClient(rawRpcClient, ipc) - ethClient := ethclient.NewClient(rawRpcClient) + rpcClient := client.NewRPCClient(rawRPCClient, ipc) + ethClient := ethclient.NewClient(rawRPCClient) return rpcClient, ethClient } diff --git a/integration_test/block_rewards_test.go b/integration_test/block_rewards_test.go index 80334546..10ccdea8 100644 --- a/integration_test/block_rewards_test.go +++ b/integration_test/block_rewards_test.go @@ -32,13 +32,13 @@ import ( var _ = Describe("Rewards calculations", func() { It("calculates a block reward for a real block", func() { - rawRpcClient, err := rpc.Dial(test_config.TestClient.IPCPath) + rawRPCClient, err := rpc.Dial(test_config.TestClient.IPCPath) Expect(err).NotTo(HaveOccurred()) - rpcClient := client.NewRpcClient(rawRpcClient, test_config.TestClient.IPCPath) - ethClient := ethclient.NewClient(rawRpcClient) + rpcClient := client.NewRPCClient(rawRPCClient, test_config.TestClient.IPCPath) + ethClient := ethclient.NewClient(rawRPCClient) blockChainClient := client.NewEthClient(ethClient) node := node.MakeNode(rpcClient) - transactionConverter := vRpc.NewRpcTransactionConverter(ethClient) + transactionConverter := vRpc.NewRPCTransactionConverter(ethClient) blockChain := eth.NewBlockChain(blockChainClient, rpcClient, node, transactionConverter) block, err := blockChain.GetBlockByNumber(1071819) Expect(err).ToNot(HaveOccurred()) @@ -46,13 +46,13 @@ var _ = Describe("Rewards calculations", func() { }) It("calculates an uncle reward for a real block", func() { - rawRpcClient, err := rpc.Dial(test_config.TestClient.IPCPath) + rawRPCClient, err := rpc.Dial(test_config.TestClient.IPCPath) Expect(err).NotTo(HaveOccurred()) - rpcClient := client.NewRpcClient(rawRpcClient, test_config.TestClient.IPCPath) - ethClient := ethclient.NewClient(rawRpcClient) + rpcClient := client.NewRPCClient(rawRPCClient, test_config.TestClient.IPCPath) + ethClient := ethclient.NewClient(rawRPCClient) blockChainClient := client.NewEthClient(ethClient) node := node.MakeNode(rpcClient) - transactionConverter := vRpc.NewRpcTransactionConverter(ethClient) + transactionConverter := vRpc.NewRPCTransactionConverter(ethClient) blockChain := eth.NewBlockChain(blockChainClient, rpcClient, node, transactionConverter) block, err := blockChain.GetBlockByNumber(1071819) Expect(err).ToNot(HaveOccurred()) diff --git a/integration_test/contract_test.go b/integration_test/contract_test.go index cc55606b..99972456 100644 --- a/integration_test/contract_test.go +++ b/integration_test/contract_test.go @@ -49,13 +49,13 @@ var _ = Describe("Reading contracts", func() { }, Index: 19, Data: "0x0000000000000000000000000000000000000000000000000c7d713b49da0000"} - rawRpcClient, err := rpc.Dial(test_config.TestClient.IPCPath) + rawRPCClient, err := rpc.Dial(test_config.TestClient.IPCPath) Expect(err).NotTo(HaveOccurred()) - rpcClient := client.NewRpcClient(rawRpcClient, test_config.TestClient.IPCPath) - ethClient := ethclient.NewClient(rawRpcClient) + rpcClient := client.NewRPCClient(rawRPCClient, test_config.TestClient.IPCPath) + ethClient := ethclient.NewClient(rawRPCClient) blockChainClient := client.NewEthClient(ethClient) node := node.MakeNode(rpcClient) - transactionConverter := rpc2.NewRpcTransactionConverter(ethClient) + transactionConverter := rpc2.NewRPCTransactionConverter(ethClient) blockChain := eth.NewBlockChain(blockChainClient, rpcClient, node, transactionConverter) contract := testing.SampleContract() @@ -67,13 +67,13 @@ var _ = Describe("Reading contracts", func() { }) It("returns and empty log array when no events for a given block / contract combo", func() { - rawRpcClient, err := rpc.Dial(test_config.TestClient.IPCPath) + rawRPCClient, err := rpc.Dial(test_config.TestClient.IPCPath) Expect(err).NotTo(HaveOccurred()) - rpcClient := client.NewRpcClient(rawRpcClient, test_config.TestClient.IPCPath) - ethClient := ethclient.NewClient(rawRpcClient) + rpcClient := client.NewRPCClient(rawRPCClient, test_config.TestClient.IPCPath) + ethClient := ethclient.NewClient(rawRPCClient) blockChainClient := client.NewEthClient(ethClient) node := node.MakeNode(rpcClient) - transactionConverter := rpc2.NewRpcTransactionConverter(ethClient) + transactionConverter := rpc2.NewRPCTransactionConverter(ethClient) blockChain := eth.NewBlockChain(blockChainClient, rpcClient, node, transactionConverter) logs, err := blockChain.GetFullSyncLogs(core.Contract{Hash: "0x123"}, big.NewInt(4703824), nil) @@ -85,13 +85,13 @@ var _ = Describe("Reading contracts", func() { Describe("Fetching Contract data", func() { It("returns the correct attribute for a real contract", func() { - rawRpcClient, err := rpc.Dial(test_config.TestClient.IPCPath) + rawRPCClient, err := rpc.Dial(test_config.TestClient.IPCPath) Expect(err).NotTo(HaveOccurred()) - rpcClient := client.NewRpcClient(rawRpcClient, test_config.TestClient.IPCPath) - ethClient := ethclient.NewClient(rawRpcClient) + rpcClient := client.NewRPCClient(rawRPCClient, test_config.TestClient.IPCPath) + ethClient := ethclient.NewClient(rawRPCClient) blockChainClient := client.NewEthClient(ethClient) node := node.MakeNode(rpcClient) - transactionConverter := rpc2.NewRpcTransactionConverter(ethClient) + transactionConverter := rpc2.NewRPCTransactionConverter(ethClient) blockChain := eth.NewBlockChain(blockChainClient, rpcClient, node, transactionConverter) contract := testing.SampleContract() diff --git a/integration_test/geth_blockchain_test.go b/integration_test/geth_blockchain_test.go index dbb3bc53..be4e1f75 100644 --- a/integration_test/geth_blockchain_test.go +++ b/integration_test/geth_blockchain_test.go @@ -37,13 +37,13 @@ var _ = Describe("Reading from the Geth blockchain", func() { var blockChain *eth.BlockChain BeforeEach(func() { - rawRpcClient, err := rpc.Dial(test_config.TestClient.IPCPath) + rawRPCClient, err := rpc.Dial(test_config.TestClient.IPCPath) Expect(err).NotTo(HaveOccurred()) - rpcClient := client.NewRpcClient(rawRpcClient, test_config.TestClient.IPCPath) - ethClient := ethclient.NewClient(rawRpcClient) + rpcClient := client.NewRPCClient(rawRPCClient, test_config.TestClient.IPCPath) + ethClient := ethclient.NewClient(rawRPCClient) blockChainClient := client.NewEthClient(ethClient) node := node.MakeNode(rpcClient) - transactionConverter := rpc2.NewRpcTransactionConverter(ethClient) + transactionConverter := rpc2.NewRPCTransactionConverter(ethClient) blockChain = eth.NewBlockChain(blockChainClient, rpcClient, node, transactionConverter) }) diff --git a/libraries/shared/factories/event/transformer_test.go b/libraries/shared/factories/event/transformer_test.go index 4684695b..0b452409 100644 --- a/libraries/shared/factories/event/transformer_test.go +++ b/libraries/shared/factories/event/transformer_test.go @@ -48,11 +48,11 @@ var _ = Describe("Transformer", func() { Config: config, }.NewTransformer(nil) - headerOne = core.Header{Id: rand.Int63(), BlockNumber: rand.Int63()} + headerOne = core.Header{ID: rand.Int63(), BlockNumber: rand.Int63()} logs = []core.HeaderSyncLog{{ ID: 0, - HeaderID: headerOne.Id, + HeaderID: headerOne.ID, Log: test_data.GenericTestLog(), Transformed: false, }} diff --git a/libraries/shared/fetcher/geth_rpc_storage_fetcher.go b/libraries/shared/fetcher/geth_rpc_storage_fetcher.go index 43438ee3..6168b81c 100644 --- a/libraries/shared/fetcher/geth_rpc_storage_fetcher.go +++ b/libraries/shared/fetcher/geth_rpc_storage_fetcher.go @@ -23,19 +23,19 @@ import ( "github.com/vulcanize/vulcanizedb/libraries/shared/streamer" ) -type GethRpcStorageFetcher struct { +type GethRPCStorageFetcher struct { statediffPayloadChan chan statediff.Payload streamer streamer.Streamer } -func NewGethRpcStorageFetcher(streamer streamer.Streamer, statediffPayloadChan chan statediff.Payload) GethRpcStorageFetcher { - return GethRpcStorageFetcher{ +func NewGethRPCStorageFetcher(streamer streamer.Streamer, statediffPayloadChan chan statediff.Payload) GethRPCStorageFetcher { + return GethRPCStorageFetcher{ statediffPayloadChan: statediffPayloadChan, streamer: streamer, } } -func (fetcher GethRpcStorageFetcher) FetchStorageDiffs(out chan<- utils.StorageDiff, errs chan<- error) { +func (fetcher GethRPCStorageFetcher) FetchStorageDiffs(out chan<- utils.StorageDiff, errs chan<- error) { ethStatediffPayloadChan := fetcher.statediffPayloadChan clientSubscription, clientSubErr := fetcher.streamer.Stream(ethStatediffPayloadChan) if clientSubErr != nil { diff --git a/libraries/shared/fetcher/geth_rpc_storage_fetcher_test.go b/libraries/shared/fetcher/geth_rpc_storage_fetcher_test.go index b1b1aa10..ca87e1b3 100644 --- a/libraries/shared/fetcher/geth_rpc_storage_fetcher_test.go +++ b/libraries/shared/fetcher/geth_rpc_storage_fetcher_test.go @@ -57,14 +57,14 @@ func (streamer *MockStoragediffStreamer) SetPayloads(payloads []statediff.Payloa var _ = Describe("Geth RPC Storage Fetcher", func() { var streamer MockStoragediffStreamer var statediffPayloadChan chan statediff.Payload - var statediffFetcher fetcher.GethRpcStorageFetcher + var statediffFetcher fetcher.GethRPCStorageFetcher var storagediffChan chan utils.StorageDiff var errorChan chan error BeforeEach(func() { streamer = MockStoragediffStreamer{} statediffPayloadChan = make(chan statediff.Payload, 1) - statediffFetcher = fetcher.NewGethRpcStorageFetcher(&streamer, statediffPayloadChan) + statediffFetcher = fetcher.NewGethRPCStorageFetcher(&streamer, statediffPayloadChan) storagediffChan = make(chan utils.StorageDiff) errorChan = make(chan error) }) diff --git a/libraries/shared/logs/extractor.go b/libraries/shared/logs/extractor.go index 11d25445..a28802ae 100644 --- a/libraries/shared/logs/extractor.go +++ b/libraries/shared/logs/extractor.go @@ -93,20 +93,20 @@ func (extractor LogExtractor) ExtractLogs(recheckHeaders constants.TransformerEx } if len(logs) > 0 { - transactionsSyncErr := extractor.Syncer.SyncTransactions(header.Id, logs) + transactionsSyncErr := extractor.Syncer.SyncTransactions(header.ID, logs) if transactionsSyncErr != nil { logError("error syncing transactions: %s", transactionsSyncErr, header) return transactionsSyncErr } - createLogsErr := extractor.LogRepository.CreateHeaderSyncLogs(header.Id, logs) + createLogsErr := extractor.LogRepository.CreateHeaderSyncLogs(header.ID, logs) if createLogsErr != nil { logError("error persisting logs: %s", createLogsErr, header) return createLogsErr } } - markHeaderCheckedErr := extractor.CheckedHeadersRepository.MarkHeaderChecked(header.Id) + markHeaderCheckedErr := extractor.CheckedHeadersRepository.MarkHeaderChecked(header.ID) if markHeaderCheckedErr != nil { logError("error marking header checked: %s", markHeaderCheckedErr, header) return markHeaderCheckedErr @@ -121,7 +121,7 @@ func earlierStartingBlockNumber(transformerBlock, watcherBlock int64) bool { func logError(description string, err error, header core.Header) { logrus.WithFields(logrus.Fields{ - "headerId": header.Id, + "headerId": header.ID, "headerHash": header.Hash, "blockNumber": header.BlockNumber, }).Errorf(description, err.Error()) diff --git a/libraries/shared/logs/extractor_test.go b/libraries/shared/logs/extractor_test.go index c9f5b317..f3b623d2 100644 --- a/libraries/shared/logs/extractor_test.go +++ b/libraries/shared/logs/extractor_test.go @@ -349,7 +349,7 @@ var _ = Describe("Log extractor", func() { addTransformerConfig(extractor) mockCheckedHeadersRepository := &fakes.MockCheckedHeadersRepository{} headerID := rand.Int63() - mockCheckedHeadersRepository.UncheckedHeadersReturnHeaders = []core.Header{{Id: headerID}} + mockCheckedHeadersRepository.UncheckedHeadersReturnHeaders = []core.Header{{ID: headerID}} extractor.CheckedHeadersRepository = mockCheckedHeadersRepository err := extractor.ExtractLogs(constants.HeaderUnchecked) @@ -362,7 +362,7 @@ var _ = Describe("Log extractor", func() { addFetchedLog(extractor) addTransformerConfig(extractor) mockCheckedHeadersRepository := &fakes.MockCheckedHeadersRepository{} - mockCheckedHeadersRepository.UncheckedHeadersReturnHeaders = []core.Header{{Id: rand.Int63()}} + mockCheckedHeadersRepository.UncheckedHeadersReturnHeaders = []core.Header{{ID: rand.Int63()}} mockCheckedHeadersRepository.MarkHeaderCheckedReturnError = fakes.FakeError extractor.CheckedHeadersRepository = mockCheckedHeadersRepository diff --git a/libraries/shared/mocks/storage_queue.go b/libraries/shared/mocks/storage_queue.go index 192c730e..ed2b9275 100644 --- a/libraries/shared/mocks/storage_queue.go +++ b/libraries/shared/mocks/storage_queue.go @@ -25,7 +25,7 @@ type MockStorageQueue struct { AddError error AddPassedDiff utils.StorageDiff DeleteErr error - DeletePassedId int + DeletePassedID int GetAllErr error DiffsToReturn []utils.StorageDiff } @@ -37,7 +37,7 @@ func (queue *MockStorageQueue) Add(diff utils.StorageDiff) error { } func (queue *MockStorageQueue) Delete(id int) error { - queue.DeletePassedId = id + queue.DeletePassedID = id return queue.DeleteErr } diff --git a/libraries/shared/repository/address_repository.go b/libraries/shared/repository/address_repository.go index e2c0bf50..4b17d583 100644 --- a/libraries/shared/repository/address_repository.go +++ b/libraries/shared/repository/address_repository.go @@ -47,23 +47,23 @@ func GetOrCreateAddress(db *postgres.DB, address string) (int64, error) { checksumAddress := getChecksumAddress(address) hashedAddress := utils.HexToKeccak256Hash(checksumAddress).Hex() - var addressId int64 - getOrCreateErr := db.Get(&addressId, getOrCreateAddressQuery, checksumAddress, hashedAddress) + var addressID int64 + getOrCreateErr := db.Get(&addressID, getOrCreateAddressQuery, checksumAddress, hashedAddress) - return addressId, getOrCreateErr + return addressID, getOrCreateErr } func GetOrCreateAddressInTransaction(tx *sqlx.Tx, address string) (int64, error) { checksumAddress := getChecksumAddress(address) hashedAddress := utils.HexToKeccak256Hash(checksumAddress).Hex() - var addressId int64 - getOrCreateErr := tx.Get(&addressId, getOrCreateAddressQuery, checksumAddress, hashedAddress) + var addressID int64 + getOrCreateErr := tx.Get(&addressID, getOrCreateAddressQuery, checksumAddress, hashedAddress) - return addressId, getOrCreateErr + return addressID, getOrCreateErr } -func GetAddressById(db *postgres.DB, id int64) (string, error) { +func GetAddressByID(db *postgres.DB, id int64) (string, error) { var address string getErr := db.Get(&address, `SELECT address FROM public.addresses WHERE id = $1`, id) return address, getErr diff --git a/libraries/shared/repository/address_repository_test.go b/libraries/shared/repository/address_repository_test.go index ad13bbd1..5abb4222 100644 --- a/libraries/shared/repository/address_repository_test.go +++ b/libraries/shared/repository/address_repository_test.go @@ -164,18 +164,18 @@ var _ = Describe("address lookup", func() { }) }) - Describe("GetAddressById", func() { + Describe("GetAddressByID", func() { It("gets and address by it's id", func() { addressId, createErr := repository.GetOrCreateAddress(db, address) Expect(createErr).NotTo(HaveOccurred()) - actualAddress, getErr := repository.GetAddressById(db, addressId) + actualAddress, getErr := repository.GetAddressByID(db, addressId) Expect(getErr).NotTo(HaveOccurred()) Expect(actualAddress).To(Equal(address)) }) It("returns an error if the id doesn't exist", func() { - _, getErr := repository.GetAddressById(db, 0) + _, getErr := repository.GetAddressByID(db, 0) Expect(getErr).To(HaveOccurred()) Expect(getErr).To(MatchError("sql: no rows in result set")) }) diff --git a/libraries/shared/storage/storage_queue_test.go b/libraries/shared/storage/storage_queue_test.go index 43faca29..d347a93b 100644 --- a/libraries/shared/storage/storage_queue_test.go +++ b/libraries/shared/storage/storage_queue_test.go @@ -72,7 +72,7 @@ var _ = Describe("Storage queue", func() { Expect(getErr).NotTo(HaveOccurred()) Expect(len(diffs)).To(Equal(1)) - err := queue.Delete(diffs[0].Id) + err := queue.Delete(diffs[0].ID) Expect(err).NotTo(HaveOccurred()) remainingRows, secondGetErr := queue.GetAll() @@ -97,13 +97,13 @@ var _ = Describe("Storage queue", func() { Expect(err).NotTo(HaveOccurred()) Expect(len(diffs)).To(Equal(2)) Expect(diffs[0]).NotTo(Equal(diffs[1])) - Expect(diffs[0].Id).NotTo(BeZero()) + Expect(diffs[0].ID).NotTo(BeZero()) Expect(diffs[0].HashedAddress).To(Or(Equal(diff.HashedAddress), Equal(diffTwo.HashedAddress))) Expect(diffs[0].BlockHash).To(Or(Equal(diff.BlockHash), Equal(diffTwo.BlockHash))) Expect(diffs[0].BlockHeight).To(Or(Equal(diff.BlockHeight), Equal(diffTwo.BlockHeight))) Expect(diffs[0].StorageKey).To(Or(Equal(diff.StorageKey), Equal(diffTwo.StorageKey))) Expect(diffs[0].StorageValue).To(Or(Equal(diff.StorageValue), Equal(diffTwo.StorageValue))) - Expect(diffs[1].Id).NotTo(BeZero()) + Expect(diffs[1].ID).NotTo(BeZero()) Expect(diffs[1].HashedAddress).To(Or(Equal(diff.HashedAddress), Equal(diffTwo.HashedAddress))) Expect(diffs[1].BlockHash).To(Or(Equal(diff.BlockHash), Equal(diffTwo.BlockHash))) Expect(diffs[1].BlockHeight).To(Or(Equal(diff.BlockHeight), Equal(diffTwo.BlockHeight))) diff --git a/libraries/shared/storage/utils/diff.go b/libraries/shared/storage/utils/diff.go index a58dfab6..991c9828 100644 --- a/libraries/shared/storage/utils/diff.go +++ b/libraries/shared/storage/utils/diff.go @@ -27,7 +27,7 @@ import ( const ExpectedRowLength = 5 type StorageDiff struct { - Id int + ID int HashedAddress common.Hash `db:"contract"` BlockHash common.Hash `db:"block_hash"` BlockHeight int `db:"block_height"` diff --git a/libraries/shared/streamer/statediff_streamer.go b/libraries/shared/streamer/statediff_streamer.go index 8cda750f..564a4e15 100644 --- a/libraries/shared/streamer/statediff_streamer.go +++ b/libraries/shared/streamer/statediff_streamer.go @@ -26,7 +26,7 @@ type Streamer interface { } type StateDiffStreamer struct { - client core.RpcClient + client core.RPCClient } func (streamer *StateDiffStreamer) Stream(payloadChan chan statediff.Payload) (*rpc.ClientSubscription, error) { @@ -34,7 +34,7 @@ func (streamer *StateDiffStreamer) Stream(payloadChan chan statediff.Payload) (* return streamer.client.Subscribe("statediff", payloadChan, "stream") } -func NewStateDiffStreamer(client core.RpcClient) StateDiffStreamer { +func NewStateDiffStreamer(client core.RPCClient) StateDiffStreamer { return StateDiffStreamer{ client: client, } diff --git a/libraries/shared/streamer/statediff_streamer_test.go b/libraries/shared/streamer/statediff_streamer_test.go index 59590c84..ab96a0b9 100644 --- a/libraries/shared/streamer/statediff_streamer_test.go +++ b/libraries/shared/streamer/statediff_streamer_test.go @@ -24,7 +24,7 @@ import ( var _ = Describe("StateDiff Streamer", func() { It("subscribes to the geth statediff service", func() { - client := &fakes.MockRpcClient{} + client := &fakes.MockRPCClient{} streamer := streamer.NewStateDiffStreamer(client) payloadChan := make(chan statediff.Payload) _, err := streamer.Stream(payloadChan) diff --git a/libraries/shared/watcher/storage_watcher.go b/libraries/shared/watcher/storage_watcher.go index 7768beb4..38467c43 100644 --- a/libraries/shared/watcher/storage_watcher.go +++ b/libraries/shared/watcher/storage_watcher.go @@ -103,12 +103,12 @@ func (storageWatcher StorageWatcher) processQueue() { storageTransformer, ok := storageWatcher.getTransformer(diff) if !ok { // delete diff from queue if address no longer watched - storageWatcher.deleteRow(diff.Id) + storageWatcher.deleteRow(diff.ID) continue } executeErr := storageTransformer.Execute(diff) if executeErr == nil { - storageWatcher.deleteRow(diff.Id) + storageWatcher.deleteRow(diff.ID) } } } diff --git a/libraries/shared/watcher/storage_watcher_test.go b/libraries/shared/watcher/storage_watcher_test.go index f3fe0afa..7cc9a115 100644 --- a/libraries/shared/watcher/storage_watcher_test.go +++ b/libraries/shared/watcher/storage_watcher_test.go @@ -65,7 +65,7 @@ var _ = Describe("Storage Watcher", func() { mockQueue = &mocks.MockStorageQueue{} mockTransformer = &mocks.MockStorageTransformer{KeccakOfAddress: hashedAddress} csvDiff = utils.StorageDiff{ - Id: 1337, + ID: 1337, HashedAddress: hashedAddress, BlockHash: common.HexToHash("0xfedcba9876543210"), BlockHeight: 0, @@ -167,8 +167,8 @@ var _ = Describe("Storage Watcher", func() { go storageWatcher.Execute(diffs, errs, time.Nanosecond) Eventually(func() int { - return mockQueue.DeletePassedId - }).Should(Equal(csvDiff.Id)) + return mockQueue.DeletePassedID + }).Should(Equal(csvDiff.ID)) close(done) }) @@ -190,7 +190,7 @@ var _ = Describe("Storage Watcher", func() { It("deletes obsolete diff from queue if contract not recognized", func(done Done) { obsoleteDiff := utils.StorageDiff{ - Id: csvDiff.Id + 1, + ID: csvDiff.ID + 1, HashedAddress: utils.HexToKeccak256Hash("0xfedcba9876543210"), } mockQueue.DiffsToReturn = []utils.StorageDiff{obsoleteDiff} @@ -198,14 +198,14 @@ var _ = Describe("Storage Watcher", func() { go storageWatcher.Execute(diffs, errs, time.Nanosecond) Eventually(func() int { - return mockQueue.DeletePassedId - }).Should(Equal(obsoleteDiff.Id)) + return mockQueue.DeletePassedID + }).Should(Equal(obsoleteDiff.ID)) close(done) }) It("logs error if deleting obsolete diff fails", func(done Done) { obsoleteDiff := utils.StorageDiff{ - Id: csvDiff.Id + 1, + ID: csvDiff.ID + 1, HashedAddress: utils.HexToKeccak256Hash("0xfedcba9876543210"), } mockQueue.DiffsToReturn = []utils.StorageDiff{obsoleteDiff} diff --git a/pkg/contract_watcher/header/repository/header_repository.go b/pkg/contract_watcher/header/repository/header_repository.go index 4a3fd8d7..14bb7d37 100644 --- a/pkg/contract_watcher/header/repository/header_repository.go +++ b/pkg/contract_watcher/header/repository/header_repository.go @@ -148,7 +148,7 @@ func (r *headerRepository) MarkHeadersCheckedForAll(headers []core.Header, ids [ pgStr += fmt.Sprintf("%s = checked_headers.%s + 1, ", id, id) } pgStr = pgStr[:len(pgStr)-2] - _, err = tx.Exec(pgStr, header.Id) + _, err = tx.Exec(pgStr, header.ID) if err != nil { rollbackErr := tx.Rollback() if rollbackErr != nil { diff --git a/pkg/contract_watcher/header/repository/header_repository_test.go b/pkg/contract_watcher/header/repository/header_repository_test.go index 9084e40f..42c4c61d 100644 --- a/pkg/contract_watcher/header/repository/header_repository_test.go +++ b/pkg/contract_watcher/header/repository/header_repository_test.go @@ -174,16 +174,16 @@ var _ = Describe("Repository", func() { Expect(err).ToNot(HaveOccurred()) Expect(len(missingHeaders)).To(Equal(3)) - err = contractHeaderRepo.MarkHeaderChecked(missingHeaders[0].Id, eventIDs[0]) + err = contractHeaderRepo.MarkHeaderChecked(missingHeaders[0].ID, eventIDs[0]) Expect(err).ToNot(HaveOccurred()) missingHeaders, err = contractHeaderRepo.MissingHeadersForAll(mocks.MockHeader1.BlockNumber, mocks.MockHeader4.BlockNumber, eventIDs) Expect(err).ToNot(HaveOccurred()) Expect(len(missingHeaders)).To(Equal(3)) - err = contractHeaderRepo.MarkHeaderChecked(missingHeaders[0].Id, eventIDs[1]) + err = contractHeaderRepo.MarkHeaderChecked(missingHeaders[0].ID, eventIDs[1]) Expect(err).ToNot(HaveOccurred()) - err = contractHeaderRepo.MarkHeaderChecked(missingHeaders[0].Id, eventIDs[2]) + err = contractHeaderRepo.MarkHeaderChecked(missingHeaders[0].ID, eventIDs[2]) Expect(err).ToNot(HaveOccurred()) missingHeaders, err = contractHeaderRepo.MissingHeadersForAll(mocks.MockHeader2.BlockNumber, mocks.MockHeader4.BlockNumber, eventIDs) @@ -236,7 +236,7 @@ var _ = Describe("Repository", func() { Expect(err).ToNot(HaveOccurred()) Expect(len(missingHeaders)).To(Equal(3)) - headerID := missingHeaders[0].Id + headerID := missingHeaders[0].ID err = contractHeaderRepo.MarkHeaderChecked(headerID, eventIDs[0]) Expect(err).ToNot(HaveOccurred()) @@ -254,7 +254,7 @@ var _ = Describe("Repository", func() { Expect(err).ToNot(HaveOccurred()) Expect(len(missingHeaders)).To(Equal(3)) - headerID := missingHeaders[0].Id + headerID := missingHeaders[0].ID err = contractHeaderRepo.MarkHeaderChecked(headerID, "notEventId") Expect(err).To(HaveOccurred()) @@ -274,7 +274,7 @@ var _ = Describe("Repository", func() { Expect(err).ToNot(HaveOccurred()) Expect(len(missingHeaders)).To(Equal(3)) - headerID := missingHeaders[0].Id + headerID := missingHeaders[0].ID err = contractHeaderRepo.MarkHeaderCheckedForAll(headerID, eventIDs) Expect(err).ToNot(HaveOccurred()) @@ -326,8 +326,8 @@ var _ = Describe("Repository", func() { Expect(err).ToNot(HaveOccurred()) Expect(len(missingHeaders)).To(Equal(3)) - headerID := missingHeaders[0].Id - headerID2 := missingHeaders[1].Id + headerID := missingHeaders[0].ID + headerID2 := missingHeaders[1].ID for i, id := range eventIDs { err = contractHeaderRepo.MarkHeaderChecked(headerID, id) Expect(err).ToNot(HaveOccurred()) @@ -340,7 +340,7 @@ var _ = Describe("Repository", func() { intersectionHeaders, err := contractHeaderRepo.MissingMethodsCheckedEventsIntersection(mocks.MockHeader1.BlockNumber, mocks.MockHeader4.BlockNumber, methodIDs, eventIDs) Expect(err).ToNot(HaveOccurred()) Expect(len(intersectionHeaders)).To(Equal(1)) - Expect(intersectionHeaders[0].Id).To(Equal(headerID2)) + Expect(intersectionHeaders[0].ID).To(Equal(headerID2)) }) }) }) diff --git a/pkg/contract_watcher/header/transformer/transformer.go b/pkg/contract_watcher/header/transformer/transformer.go index f3fe0188..b77870c7 100644 --- a/pkg/contract_watcher/header/transformer/transformer.go +++ b/pkg/contract_watcher/header/transformer/transformer.go @@ -239,7 +239,7 @@ func (tr *Transformer) Execute() error { // If no logs are found mark the header checked for all of these eventIDs // and continue to method polling and onto the next iteration if len(allLogs) < 1 { - markCheckedErr := tr.HeaderRepository.MarkHeaderCheckedForAll(header.Id, tr.eventIds) + markCheckedErr := tr.HeaderRepository.MarkHeaderCheckedForAll(header.ID, tr.eventIds) if markCheckedErr != nil { return fmt.Errorf("error marking header checked: %s", markCheckedErr.Error()) } @@ -268,7 +268,7 @@ func (tr *Transformer) Execute() error { tr.Converter.Update(con) // Convert logs into batches of log mappings (eventName => []types.Logs - convertedLogs, convertErr := tr.Converter.ConvertBatch(logs, con.Events, header.Id) + convertedLogs, convertErr := tr.Converter.ConvertBatch(logs, con.Events, header.ID) if convertErr != nil { return fmt.Errorf("error converting logs: %s", convertErr.Error()) } @@ -287,7 +287,7 @@ func (tr *Transformer) Execute() error { } } - markCheckedErr := tr.HeaderRepository.MarkHeaderCheckedForAll(header.Id, tr.eventIds) + markCheckedErr := tr.HeaderRepository.MarkHeaderCheckedForAll(header.ID, tr.eventIds) if markCheckedErr != nil { return fmt.Errorf("error marking header checked: %s", markCheckedErr.Error()) } @@ -321,7 +321,7 @@ func (tr *Transformer) methodPolling(header core.Header, sortedMethodIds map[str } // Mark this header checked for the methods - markCheckedErr := tr.HeaderRepository.MarkHeaderCheckedForAll(header.Id, sortedMethodIds[con.Address]) + markCheckedErr := tr.HeaderRepository.MarkHeaderCheckedForAll(header.ID, sortedMethodIds[con.Address]) if markCheckedErr != nil { return fmt.Errorf("error marking header checked: %s", markCheckedErr.Error()) } diff --git a/pkg/contract_watcher/shared/getter/getter_test.go b/pkg/contract_watcher/shared/getter/getter_test.go index 4af9a863..d28f10ac 100644 --- a/pkg/contract_watcher/shared/getter/getter_test.go +++ b/pkg/contract_watcher/shared/getter/getter_test.go @@ -40,11 +40,11 @@ var _ = Describe("Interface Getter", func() { blockNumber := int64(6885696) rawRpcClient, err := rpc.Dial(testIPC) Expect(err).NotTo(HaveOccurred()) - rpcClient := client.NewRpcClient(rawRpcClient, testIPC) + rpcClient := client.NewRPCClient(rawRpcClient, testIPC) ethClient := ethclient.NewClient(rawRpcClient) blockChainClient := client.NewEthClient(ethClient) node := node.MakeNode(rpcClient) - transactionConverter := rpc2.NewRpcTransactionConverter(ethClient) + transactionConverter := rpc2.NewRPCTransactionConverter(ethClient) blockChain := eth.NewBlockChain(blockChainClient, rpcClient, node, transactionConverter) interfaceGetter := getter.NewInterfaceGetter(blockChain) abi, err := interfaceGetter.GetABI(constants.PublicResolverAddress, blockNumber) diff --git a/pkg/contract_watcher/shared/helpers/test_helpers/database.go b/pkg/contract_watcher/shared/helpers/test_helpers/database.go index 37cb0af1..d631bc72 100644 --- a/pkg/contract_watcher/shared/helpers/test_helpers/database.go +++ b/pkg/contract_watcher/shared/helpers/test_helpers/database.go @@ -38,8 +38,8 @@ import ( ) type TransferLog struct { - Id int64 `db:"id"` - VulcanizeLogId int64 `db:"vulcanize_log_id"` + ID int64 `db:"id"` + VulcanizeLogID int64 `db:"vulcanize_log_id"` TokenName string `db:"token_name"` Block int64 `db:"block"` Tx string `db:"tx"` @@ -49,8 +49,8 @@ type TransferLog struct { } type NewOwnerLog struct { - Id int64 `db:"id"` - VulcanizeLogId int64 `db:"vulcanize_log_id"` + ID int64 `db:"id"` + VulcanizeLogID int64 `db:"vulcanize_log_id"` TokenName string `db:"token_name"` Block int64 `db:"block"` Tx string `db:"tx"` @@ -60,7 +60,7 @@ type NewOwnerLog struct { } type HeaderSyncTransferLog struct { - Id int64 `db:"id"` + ID int64 `db:"id"` HeaderID int64 `db:"header_id"` TokenName string `db:"token_name"` LogIndex int64 `db:"log_idx"` @@ -72,7 +72,7 @@ type HeaderSyncTransferLog struct { } type HeaderSyncNewOwnerLog struct { - Id int64 `db:"id"` + ID int64 `db:"id"` HeaderID int64 `db:"header_id"` TokenName string `db:"token_name"` LogIndex int64 `db:"log_idx"` @@ -84,7 +84,7 @@ type HeaderSyncNewOwnerLog struct { } type BalanceOf struct { - Id int64 `db:"id"` + ID int64 `db:"id"` TokenName string `db:"token_name"` Block int64 `db:"block"` Address string `db:"who_"` @@ -92,7 +92,7 @@ type BalanceOf struct { } type Resolver struct { - Id int64 `db:"id"` + ID int64 `db:"id"` TokenName string `db:"token_name"` Block int64 `db:"block"` Node string `db:"node_"` @@ -100,7 +100,7 @@ type Resolver struct { } type Owner struct { - Id int64 `db:"id"` + ID int64 `db:"id"` TokenName string `db:"token_name"` Block int64 `db:"block"` Node string `db:"node_"` @@ -110,13 +110,13 @@ type Owner struct { func SetupDBandBC() (*postgres.DB, core.BlockChain) { con := test_config.TestClient testIPC := con.IPCPath - rawRpcClient, err := rpc.Dial(testIPC) + rawRPCClient, err := rpc.Dial(testIPC) Expect(err).NotTo(HaveOccurred()) - rpcClient := client.NewRpcClient(rawRpcClient, testIPC) - ethClient := ethclient.NewClient(rawRpcClient) + rpcClient := client.NewRPCClient(rawRPCClient, testIPC) + ethClient := ethclient.NewClient(rawRPCClient) blockChainClient := client.NewEthClient(ethClient) madeNode := node.MakeNode(rpcClient) - transactionConverter := rpc2.NewRpcTransactionConverter(ethClient) + transactionConverter := rpc2.NewRPCTransactionConverter(ethClient) blockChain := eth.NewBlockChain(blockChainClient, rpcClient, madeNode, transactionConverter) db, err := postgres.NewDB(config.Database{ @@ -129,7 +129,7 @@ func SetupDBandBC() (*postgres.DB, core.BlockChain) { return db, blockChain } -func SetupTusdRepo(vulcanizeLogId *int64, wantedEvents, wantedMethods []string) (*postgres.DB, *contract.Contract) { +func SetupTusdRepo(vulcanizeLogID *int64, wantedEvents, wantedMethods []string) (*postgres.DB, *contract.Contract) { db, err := postgres.NewDB(config.Database{ Hostname: "localhost", Name: "vulcanize_testing", @@ -142,14 +142,14 @@ func SetupTusdRepo(vulcanizeLogId *int64, wantedEvents, wantedMethods []string) blockRepository := *repositories.NewBlockRepository(db) blockNumber := rand.Int63() - blockId := CreateBlock(blockNumber, blockRepository) + blockID := CreateBlock(blockNumber, blockRepository) receipts := []core.Receipt{{Logs: []core.FullSyncLog{{}}}} - err = receiptRepository.CreateReceiptsAndLogs(blockId, receipts) + err = receiptRepository.CreateReceiptsAndLogs(blockID, receipts) Expect(err).ToNot(HaveOccurred()) - err = logRepository.Get(vulcanizeLogId, `SELECT id FROM full_sync_logs`) + err = logRepository.Get(vulcanizeLogID, `SELECT id FROM full_sync_logs`) Expect(err).ToNot(HaveOccurred()) info := SetupTusdContract(wantedEvents, wantedMethods) @@ -175,7 +175,7 @@ func SetupTusdContract(wantedEvents, wantedMethods []string) *contract.Contract }.Init() } -func SetupENSRepo(vulcanizeLogId *int64, wantedEvents, wantedMethods []string) (*postgres.DB, *contract.Contract) { +func SetupENSRepo(vulcanizeLogID *int64, wantedEvents, wantedMethods []string) (*postgres.DB, *contract.Contract) { db, err := postgres.NewDB(config.Database{ Hostname: "localhost", Name: "vulcanize_testing", @@ -188,14 +188,14 @@ func SetupENSRepo(vulcanizeLogId *int64, wantedEvents, wantedMethods []string) ( blockRepository := *repositories.NewBlockRepository(db) blockNumber := rand.Int63() - blockId := CreateBlock(blockNumber, blockRepository) + blockID := CreateBlock(blockNumber, blockRepository) receipts := []core.Receipt{{Logs: []core.FullSyncLog{{}}}} - err = receiptRepository.CreateReceiptsAndLogs(blockId, receipts) + err = receiptRepository.CreateReceiptsAndLogs(blockID, receipts) Expect(err).ToNot(HaveOccurred()) - err = logRepository.Get(vulcanizeLogId, `SELECT id FROM full_sync_logs`) + err = logRepository.Get(vulcanizeLogID, `SELECT id FROM full_sync_logs`) Expect(err).ToNot(HaveOccurred()) info := SetupENSContract(wantedEvents, wantedMethods) @@ -316,9 +316,9 @@ func TearDown(db *postgres.DB) { Expect(err).NotTo(HaveOccurred()) } -func CreateBlock(blockNumber int64, repository repositories.BlockRepository) (blockId int64) { - blockId, err := repository.CreateOrUpdateBlock(core.Block{Number: blockNumber}) +func CreateBlock(blockNumber int64, repository repositories.BlockRepository) int64 { + blockID, err := repository.CreateOrUpdateBlock(core.Block{Number: blockNumber}) Expect(err).NotTo(HaveOccurred()) - return blockId + return blockID } diff --git a/pkg/contract_watcher/shared/repository/event_repository_test.go b/pkg/contract_watcher/shared/repository/event_repository_test.go index bc61d776..3f3560fa 100644 --- a/pkg/contract_watcher/shared/repository/event_repository_test.go +++ b/pkg/contract_watcher/shared/repository/event_repository_test.go @@ -157,8 +157,8 @@ var _ = Describe("Repository", func() { err = db.QueryRowx(fmt.Sprintf("SELECT * FROM full_%s.transfer_event", constants.TusdContractAddress)).StructScan(&scanLog) Expect(err).ToNot(HaveOccurred()) expectedLog := test_helpers.TransferLog{ - Id: 1, - VulcanizeLogId: vulcanizeLogId, + ID: 1, + VulcanizeLogID: vulcanizeLogId, TokenName: "TrueUSD", Block: 5488076, Tx: "0x135391a0962a63944e5908e6fedfff90fb4be3e3290a21017861099bad6546ae", @@ -179,8 +179,8 @@ var _ = Describe("Repository", func() { err = db.QueryRowx(fmt.Sprintf("SELECT * FROM full_%s.transfer_event", constants.TusdContractAddress)).StructScan(&scanLog) Expect(err).ToNot(HaveOccurred()) expectedLog := test_helpers.TransferLog{ - Id: 1, - VulcanizeLogId: vulcanizeLogId, + ID: 1, + VulcanizeLogID: vulcanizeLogId, TokenName: "TrueUSD", Block: 5488076, Tx: "0x135391a0962a63944e5908e6fedfff90fb4be3e3290a21017861099bad6546ae", diff --git a/pkg/contract_watcher/shared/repository/method_repository_test.go b/pkg/contract_watcher/shared/repository/method_repository_test.go index da3538a9..740a4ecf 100644 --- a/pkg/contract_watcher/shared/repository/method_repository_test.go +++ b/pkg/contract_watcher/shared/repository/method_repository_test.go @@ -133,7 +133,7 @@ var _ = Describe("Repository", func() { err = db.QueryRowx(fmt.Sprintf("SELECT * FROM full_%s.balanceof_method", constants.TusdContractAddress)).StructScan(&scanStruct) expectedLog := test_helpers.BalanceOf{ - Id: 1, + ID: 1, TokenName: "TrueUSD", Block: 6707323, Address: "0xfE9e8709d3215310075d67E3ed32A380CCf451C8", @@ -222,7 +222,7 @@ var _ = Describe("Repository", func() { err = db.QueryRowx(fmt.Sprintf("SELECT * FROM header_%s.balanceof_method", constants.TusdContractAddress)).StructScan(&scanStruct) expectedLog := test_helpers.BalanceOf{ - Id: 1, + ID: 1, TokenName: "TrueUSD", Block: 6707323, Address: "0xfE9e8709d3215310075d67E3ed32A380CCf451C8", diff --git a/pkg/core/header.go b/pkg/core/header.go index ea8f3646..73aa220e 100644 --- a/pkg/core/header.go +++ b/pkg/core/header.go @@ -23,7 +23,7 @@ import ( ) type Header struct { - Id int64 + ID int64 BlockNumber int64 `db:"block_number"` Hash string Raw []byte diff --git a/pkg/core/rpc_client.go b/pkg/core/rpc_client.go index b78543cd..bd627d48 100644 --- a/pkg/core/rpc_client.go +++ b/pkg/core/rpc_client.go @@ -23,7 +23,7 @@ import ( "github.com/vulcanize/vulcanizedb/pkg/eth/client" ) -type RpcClient interface { +type RPCClient interface { CallContext(ctx context.Context, result interface{}, method string, args ...interface{}) error BatchCall(batch []client.BatchElem) error IpcPath() string diff --git a/pkg/core/transaction.go b/pkg/core/transaction.go index 2ef428d1..89c6e3cb 100644 --- a/pkg/core/transaction.go +++ b/pkg/core/transaction.go @@ -30,7 +30,7 @@ type TransactionModel struct { Value string } -type RpcTransaction struct { +type RPCTransaction struct { Nonce string `json:"nonce"` GasPrice string `json:"gasPrice"` GasLimit string `json:"gas"` diff --git a/pkg/core/uncle.go b/pkg/core/uncle.go index dfece8e7..044e712d 100644 --- a/pkg/core/uncle.go +++ b/pkg/core/uncle.go @@ -17,7 +17,7 @@ package core type Uncle struct { - Id int64 + ID int64 Miner string Reward string Hash string diff --git a/pkg/datastore/postgres/postgres.go b/pkg/datastore/postgres/postgres.go index 66cf535f..47fcd1bb 100644 --- a/pkg/datastore/postgres/postgres.go +++ b/pkg/datastore/postgres/postgres.go @@ -46,7 +46,7 @@ func NewDB(databaseConfig config.Database, node core.Node) (*DB, error) { } func (db *DB) CreateNode(node *core.Node) error { - var nodeId int64 + var nodeID int64 err := db.QueryRow( `INSERT INTO eth_nodes (genesis_block, network_id, eth_node_id, client_name) VALUES ($1, $2, $3, $4) @@ -57,10 +57,10 @@ func (db *DB) CreateNode(node *core.Node) error { eth_node_id = $3, client_name = $4 RETURNING id`, - node.GenesisBlock, node.NetworkID, node.ID, node.ClientName).Scan(&nodeId) + node.GenesisBlock, node.NetworkID, node.ID, node.ClientName).Scan(&nodeID) if err != nil { return ErrUnableToSetNode(err) } - db.NodeID = nodeId + db.NodeID = nodeID return nil } diff --git a/pkg/datastore/postgres/repositories/block_repository.go b/pkg/datastore/postgres/repositories/block_repository.go index c0e9e2d4..ed98a4ab 100644 --- a/pkg/datastore/postgres/repositories/block_repository.go +++ b/pkg/datastore/postgres/repositories/block_repository.go @@ -52,7 +52,7 @@ func (blockRepository BlockRepository) SetBlocksStatus(chainHead int64) error { func (blockRepository BlockRepository) CreateOrUpdateBlock(block core.Block) (int64, error) { var err error - var blockId int64 + var blockID int64 retrievedBlockHash, ok := blockRepository.getBlockHash(block) if !ok { return blockRepository.insertBlock(block) @@ -64,10 +64,10 @@ func (blockRepository BlockRepository) CreateOrUpdateBlock(block core.Block) (in } return blockRepository.insertBlock(block) } - return blockId, ErrBlockExists + return blockID, ErrBlockExists } -func (blockRepository BlockRepository) MissingBlockNumbers(startingBlockNumber int64, highestBlockNumber int64, nodeId string) []int64 { +func (blockRepository BlockRepository) MissingBlockNumbers(startingBlockNumber int64, highestBlockNumber int64, nodeID string) []int64 { numbers := make([]int64, 0) err := blockRepository.database.Select(&numbers, `SELECT all_block_numbers @@ -77,7 +77,7 @@ func (blockRepository BlockRepository) MissingBlockNumbers(startingBlockNumber i SELECT number FROM blocks WHERE eth_node_fingerprint = $3 ) `, startingBlockNumber, - highestBlockNumber, nodeId) + highestBlockNumber, nodeID) if err != nil { logrus.Error("MissingBlockNumbers: error getting blocks: ", err) } @@ -118,7 +118,7 @@ func (blockRepository BlockRepository) GetBlock(blockNumber int64) (core.Block, } func (blockRepository BlockRepository) insertBlock(block core.Block) (int64, error) { - var blockId int64 + var blockID int64 tx, beginErr := blockRepository.database.Beginx() if beginErr != nil { return 0, postgres.ErrBeginTransactionFailed(beginErr) @@ -145,7 +145,7 @@ func (blockRepository BlockRepository) insertBlock(block core.Block) (int64, err nullStringToZero(block.Reward), nullStringToZero(block.UnclesReward), blockRepository.database.Node.ID). - Scan(&blockId) + Scan(&blockID) if insertBlockErr != nil { rollbackErr := tx.Rollback() if rollbackErr != nil { @@ -154,14 +154,14 @@ func (blockRepository BlockRepository) insertBlock(block core.Block) (int64, err return 0, postgres.ErrDBInsertFailed(insertBlockErr) } if len(block.Uncles) > 0 { - insertUncleErr := blockRepository.createUncles(tx, blockId, block.Hash, block.Uncles) + insertUncleErr := blockRepository.createUncles(tx, blockID, block.Hash, block.Uncles) if insertUncleErr != nil { tx.Rollback() return 0, postgres.ErrDBInsertFailed(insertUncleErr) } } if len(block.Transactions) > 0 { - insertTxErr := blockRepository.createTransactions(tx, blockId, block.Transactions) + insertTxErr := blockRepository.createTransactions(tx, blockID, block.Transactions) if insertTxErr != nil { rollbackErr := tx.Rollback() if rollbackErr != nil { @@ -178,12 +178,12 @@ func (blockRepository BlockRepository) insertBlock(block core.Block) (int64, err } return 0, commitErr } - return blockId, nil + return blockID, nil } -func (blockRepository BlockRepository) createUncles(tx *sqlx.Tx, blockId int64, blockHash string, uncles []core.Uncle) error { +func (blockRepository BlockRepository) createUncles(tx *sqlx.Tx, blockID int64, blockHash string, uncles []core.Uncle) error { for _, uncle := range uncles { - err := blockRepository.createUncle(tx, blockId, uncle) + err := blockRepository.createUncle(tx, blockID, uncle) if err != nil { return err } @@ -191,19 +191,19 @@ func (blockRepository BlockRepository) createUncles(tx *sqlx.Tx, blockId int64, return nil } -func (blockRepository BlockRepository) createUncle(tx *sqlx.Tx, blockId int64, uncle core.Uncle) error { +func (blockRepository BlockRepository) createUncle(tx *sqlx.Tx, blockID int64, uncle core.Uncle) error { _, err := tx.Exec( `INSERT INTO uncles (hash, block_id, reward, miner, raw, block_timestamp, eth_node_id, eth_node_fingerprint) VALUES ($1, $2, $3, $4, $5, $6, $7::NUMERIC, $8) RETURNING id`, - uncle.Hash, blockId, nullStringToZero(uncle.Reward), uncle.Miner, uncle.Raw, uncle.Timestamp, blockRepository.database.NodeID, blockRepository.database.Node.ID) + uncle.Hash, blockID, nullStringToZero(uncle.Reward), uncle.Miner, uncle.Raw, uncle.Timestamp, blockRepository.database.NodeID, blockRepository.database.Node.ID) return err } -func (blockRepository BlockRepository) createTransactions(tx *sqlx.Tx, blockId int64, transactions []core.TransactionModel) error { +func (blockRepository BlockRepository) createTransactions(tx *sqlx.Tx, blockID int64, transactions []core.TransactionModel) error { for _, transaction := range transactions { - err := blockRepository.createTransaction(tx, blockId, transaction) + err := blockRepository.createTransaction(tx, blockID, transaction) if err != nil { return err } @@ -221,24 +221,24 @@ func nullStringToZero(s string) string { return s } -func (blockRepository BlockRepository) createTransaction(tx *sqlx.Tx, blockId int64, transaction core.TransactionModel) error { +func (blockRepository BlockRepository) createTransaction(tx *sqlx.Tx, blockID int64, transaction core.TransactionModel) error { _, err := tx.Exec( `INSERT INTO full_sync_transactions (block_id, gas_limit, gas_price, hash, input_data, nonce, raw, tx_from, tx_index, tx_to, "value") VALUES ($1, $2::NUMERIC, $3::NUMERIC, $4, $5, $6::NUMERIC, $7, $8, $9::NUMERIC, $10, $11::NUMERIC) - RETURNING id`, blockId, transaction.GasLimit, transaction.GasPrice, transaction.Hash, transaction.Data, + RETURNING id`, blockID, transaction.GasLimit, transaction.GasPrice, transaction.Hash, transaction.Data, transaction.Nonce, transaction.Raw, transaction.From, transaction.TxIndex, transaction.To, nullStringToZero(transaction.Value)) if err != nil { return err } if hasReceipt(transaction) { receiptRepo := FullSyncReceiptRepository{} - receiptId, err := receiptRepo.CreateFullSyncReceiptInTx(blockId, transaction.Receipt, tx) + receiptID, err := receiptRepo.CreateFullSyncReceiptInTx(blockID, transaction.Receipt, tx) if err != nil { return err } if hasLogs(transaction) { - err = blockRepository.createLogs(tx, transaction.Receipt.Logs, receiptId) + err = blockRepository.createLogs(tx, transaction.Receipt.Logs, receiptID) if err != nil { return err } @@ -266,13 +266,13 @@ func (blockRepository BlockRepository) getBlockHash(block core.Block) (string, b return retrievedBlockHash, blockExists(retrievedBlockHash) } -func (blockRepository BlockRepository) createLogs(tx *sqlx.Tx, logs []core.FullSyncLog, receiptId int64) error { +func (blockRepository BlockRepository) createLogs(tx *sqlx.Tx, logs []core.FullSyncLog, receiptID int64) error { for _, tlog := range logs { _, err := tx.Exec( `INSERT INTO full_sync_logs (block_number, address, tx_hash, index, topic0, topic1, topic2, topic3, data, receipt_id) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10) `, - tlog.BlockNumber, tlog.Address, tlog.TxHash, tlog.Index, tlog.Topics[0], tlog.Topics[1], tlog.Topics[2], tlog.Topics[3], tlog.Data, receiptId, + tlog.BlockNumber, tlog.Address, tlog.TxHash, tlog.Index, tlog.Topics[0], tlog.Topics[1], tlog.Topics[2], tlog.Topics[3], tlog.Data, receiptID, ) if err != nil { return postgres.ErrDBInsertFailed(err) diff --git a/pkg/datastore/postgres/repositories/full_sync_log_repository.go b/pkg/datastore/postgres/repositories/full_sync_log_repository.go index 4c8c1d4f..9eff2035 100644 --- a/pkg/datastore/postgres/repositories/full_sync_log_repository.go +++ b/pkg/datastore/postgres/repositories/full_sync_log_repository.go @@ -27,14 +27,14 @@ type FullSyncLogRepository struct { *postgres.DB } -func (repository FullSyncLogRepository) CreateLogs(lgs []core.FullSyncLog, receiptId int64) error { +func (repository FullSyncLogRepository) CreateLogs(lgs []core.FullSyncLog, receiptID int64) error { tx, _ := repository.DB.Beginx() for _, tlog := range lgs { _, insertLogErr := tx.Exec( `INSERT INTO full_sync_logs (block_number, address, tx_hash, index, topic0, topic1, topic2, topic3, data, receipt_id) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10) `, - tlog.BlockNumber, tlog.Address, tlog.TxHash, tlog.Index, tlog.Topics[0], tlog.Topics[1], tlog.Topics[2], tlog.Topics[3], tlog.Data, receiptId, + tlog.BlockNumber, tlog.Address, tlog.TxHash, tlog.Index, tlog.Topics[0], tlog.Topics[1], tlog.Topics[2], tlog.Topics[3], tlog.Data, receiptID, ) if insertLogErr != nil { rollbackErr := tx.Rollback() diff --git a/pkg/datastore/postgres/repositories/full_sync_receipt_repository.go b/pkg/datastore/postgres/repositories/full_sync_receipt_repository.go index d6c6ba19..c47b3baf 100644 --- a/pkg/datastore/postgres/repositories/full_sync_receipt_repository.go +++ b/pkg/datastore/postgres/repositories/full_sync_receipt_repository.go @@ -30,19 +30,19 @@ type FullSyncReceiptRepository struct { *postgres.DB } -func (receiptRepository FullSyncReceiptRepository) CreateReceiptsAndLogs(blockId int64, receipts []core.Receipt) error { +func (receiptRepository FullSyncReceiptRepository) CreateReceiptsAndLogs(blockID int64, receipts []core.Receipt) error { tx, err := receiptRepository.DB.Beginx() if err != nil { return err } for _, receipt := range receipts { - receiptId, err := receiptRepository.CreateFullSyncReceiptInTx(blockId, receipt, tx) + receiptID, err := receiptRepository.CreateFullSyncReceiptInTx(blockID, receipt, tx) if err != nil { tx.Rollback() return err } if len(receipt.Logs) > 0 { - err = createLogs(receipt.Logs, receiptId, tx) + err = createLogs(receipt.Logs, receiptID, tx) if err != nil { tx.Rollback() return err @@ -53,28 +53,28 @@ func (receiptRepository FullSyncReceiptRepository) CreateReceiptsAndLogs(blockId return nil } -func createReceipt(receipt core.Receipt, blockId int64, tx *sqlx.Tx) (int64, error) { - var receiptId int64 +func createReceipt(receipt core.Receipt, blockID int64, tx *sqlx.Tx) (int64, error) { + var receiptID int64 err := tx.QueryRow( `INSERT INTO full_sync_receipts (contract_address, tx_hash, cumulative_gas_used, gas_used, state_root, status, block_id) VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING id`, - receipt.ContractAddress, receipt.TxHash, receipt.CumulativeGasUsed, receipt.GasUsed, receipt.StateRoot, receipt.Status, blockId, - ).Scan(&receiptId) + receipt.ContractAddress, receipt.TxHash, receipt.CumulativeGasUsed, receipt.GasUsed, receipt.StateRoot, receipt.Status, blockID, + ).Scan(&receiptID) if err != nil { logrus.Error("createReceipt: Error inserting: ", err) } - return receiptId, err + return receiptID, err } -func createLogs(logs []core.FullSyncLog, receiptId int64, tx *sqlx.Tx) error { +func createLogs(logs []core.FullSyncLog, receiptID int64, tx *sqlx.Tx) error { for _, log := range logs { _, err := tx.Exec( `INSERT INTO full_sync_logs (block_number, address, tx_hash, index, topic0, topic1, topic2, topic3, data, receipt_id) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10) `, - log.BlockNumber, log.Address, log.TxHash, log.Index, log.Topics[0], log.Topics[1], log.Topics[2], log.Topics[3], log.Data, receiptId, + log.BlockNumber, log.Address, log.TxHash, log.Index, log.Topics[0], log.Topics[1], log.Topics[2], log.Topics[3], log.Data, receiptID, ) if err != nil { return err @@ -83,25 +83,25 @@ func createLogs(logs []core.FullSyncLog, receiptId int64, tx *sqlx.Tx) error { return nil } -func (FullSyncReceiptRepository) CreateFullSyncReceiptInTx(blockId int64, receipt core.Receipt, tx *sqlx.Tx) (int64, error) { - var receiptId int64 - addressId, getAddressErr := repository.GetOrCreateAddressInTransaction(tx, receipt.ContractAddress) +func (FullSyncReceiptRepository) CreateFullSyncReceiptInTx(blockID int64, receipt core.Receipt, tx *sqlx.Tx) (int64, error) { + var receiptID int64 + addressID, getAddressErr := repository.GetOrCreateAddressInTransaction(tx, receipt.ContractAddress) if getAddressErr != nil { logrus.Error("createReceipt: Error getting address id: ", getAddressErr) - return receiptId, getAddressErr + return receiptID, getAddressErr } err := tx.QueryRow( `INSERT INTO full_sync_receipts (contract_address_id, tx_hash, cumulative_gas_used, gas_used, state_root, status, block_id) VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING id`, - addressId, receipt.TxHash, receipt.CumulativeGasUsed, receipt.GasUsed, receipt.StateRoot, receipt.Status, blockId).Scan(&receiptId) + addressID, receipt.TxHash, receipt.CumulativeGasUsed, receipt.GasUsed, receipt.StateRoot, receipt.Status, blockID).Scan(&receiptID) if err != nil { tx.Rollback() logrus.Warning("CreateReceipt: error inserting receipt: ", err) - return receiptId, err + return receiptID, err } - return receiptId, nil + return receiptID, nil } func (receiptRepository FullSyncReceiptRepository) GetFullSyncReceipt(txHash string) (core.Receipt, error) { diff --git a/pkg/datastore/postgres/repositories/header_repository.go b/pkg/datastore/postgres/repositories/header_repository.go index 2323f10d..1ed931b9 100644 --- a/pkg/datastore/postgres/repositories/header_repository.go +++ b/pkg/datastore/postgres/repositories/header_repository.go @@ -68,7 +68,7 @@ func (repository HeaderRepository) CreateTransactions(headerID int64, transactio } func (repository HeaderRepository) CreateTransactionInTx(tx *sqlx.Tx, headerID int64, transaction core.TransactionModel) (int64, error) { - var txId int64 + var txID int64 err := tx.QueryRowx(`INSERT INTO public.header_sync_transactions (header_id, hash, gas_limit, gas_price, input_data, nonce, raw, tx_from, tx_index, tx_to, "value") VALUES ($1, $2, $3::NUMERIC, $4::NUMERIC, $5, $6::NUMERIC, $7, $8, $9::NUMERIC, $10, $11::NUMERIC) @@ -77,12 +77,12 @@ func (repository HeaderRepository) CreateTransactionInTx(tx *sqlx.Tx, headerID i RETURNING id`, headerID, transaction.Hash, transaction.GasLimit, transaction.GasPrice, transaction.Data, transaction.Nonce, transaction.Raw, transaction.From, - transaction.TxIndex, transaction.To, transaction.Value).Scan(&txId) + transaction.TxIndex, transaction.To, transaction.Value).Scan(&txID) if err != nil { log.Error("header_repository: error inserting transaction: ", err) - return txId, err + return txID, err } - return txId, err + return txID, err } func (repository HeaderRepository) GetHeader(blockNumber int64) (core.Header, error) { @@ -132,19 +132,19 @@ func (repository HeaderRepository) getHeaderHash(header core.Header) (string, er // Can happen when concurrent processes are inserting headers // Otherwise should not occur since only called in CreateOrUpdateHeader func (repository HeaderRepository) InternalInsertHeader(header core.Header) (int64, error) { - var headerId int64 + var headerID int64 row := repository.database.QueryRowx( `INSERT INTO public.headers (block_number, hash, block_timestamp, raw, eth_node_id, eth_node_fingerprint) VALUES ($1, $2, $3::NUMERIC, $4, $5, $6) ON CONFLICT DO NOTHING RETURNING id`, header.BlockNumber, header.Hash, header.Timestamp, header.Raw, repository.database.NodeID, repository.database.Node.ID) - err := row.Scan(&headerId) + err := row.Scan(&headerID) if err != nil { if err == sql.ErrNoRows { return 0, ErrValidHeaderExists } log.Error("InternalInsertHeader: error inserting header: ", err) } - return headerId, err + return headerID, err } func (repository HeaderRepository) replaceHeader(header core.Header) (int64, error) { diff --git a/pkg/datastore/postgres/repositories/header_repository_test.go b/pkg/datastore/postgres/repositories/header_repository_test.go index c37812a5..f059752a 100644 --- a/pkg/datastore/postgres/repositories/header_repository_test.go +++ b/pkg/datastore/postgres/repositories/header_repository_test.go @@ -423,7 +423,7 @@ var _ = Describe("Block header repository", func() { dbHeader, err := repo.GetHeader(header.BlockNumber) Expect(err).NotTo(HaveOccurred()) - Expect(dbHeader.Id).NotTo(BeZero()) + Expect(dbHeader.ID).NotTo(BeZero()) Expect(dbHeader.BlockNumber).To(Equal(header.BlockNumber)) Expect(dbHeader.Hash).To(Equal(header.Hash)) Expect(dbHeader.Raw).To(MatchJSON(header.Raw)) diff --git a/pkg/datastore/postgres/repositories/header_sync_log_repository.go b/pkg/datastore/postgres/repositories/header_sync_log_repository.go index 98dae081..17d5113b 100644 --- a/pkg/datastore/postgres/repositories/header_sync_log_repository.go +++ b/pkg/datastore/postgres/repositories/header_sync_log_repository.go @@ -73,7 +73,7 @@ func (repo HeaderSyncLogRepository) GetUntransformedHeaderSyncLogs() ([]core.Hea for _, topic := range rawLog.Topics { logTopics = append(logTopics, common.BytesToHash(topic)) } - address, addrErr := repository.GetAddressById(repo.db, rawLog.Address) + address, addrErr := repository.GetAddressByID(repo.db, rawLog.Address) if addrErr != nil { return nil, addrErr } diff --git a/pkg/datastore/postgres/repositories/header_sync_log_repository_test.go b/pkg/datastore/postgres/repositories/header_sync_log_repository_test.go index a6f2d0d7..d2e6c579 100644 --- a/pkg/datastore/postgres/repositories/header_sync_log_repository_test.go +++ b/pkg/datastore/postgres/repositories/header_sync_log_repository_test.go @@ -80,7 +80,7 @@ var _ = Describe("Header sync log repository", func() { Expect(lookupErr).NotTo(HaveOccurred()) Expect(dbLog.ID).NotTo(BeZero()) Expect(dbLog.HeaderID).To(Equal(headerID)) - actualAddress, addressErr := repository2.GetAddressById(db, dbLog.Address) + actualAddress, addressErr := repository2.GetAddressByID(db, dbLog.Address) Expect(addressErr).NotTo(HaveOccurred()) Expect(actualAddress).To(Equal(log.Address.Hex())) Expect(dbLog.Topics[0]).To(Equal(log.Topics[0].Bytes())) @@ -128,7 +128,7 @@ var _ = Describe("Header sync log repository", func() { logTopics = append(logTopics, common.BytesToHash(topic)) } - actualAddress, addressErr := repository2.GetAddressById(db, dbLog.Address) + actualAddress, addressErr := repository2.GetAddressByID(db, dbLog.Address) Expect(addressErr).NotTo(HaveOccurred()) reconstructedLog := types.Log{ Address: common.HexToAddress(actualAddress), diff --git a/pkg/datastore/postgres/repositories/header_sync_receipt_repository.go b/pkg/datastore/postgres/repositories/header_sync_receipt_repository.go index 13029045..787c2650 100644 --- a/pkg/datastore/postgres/repositories/header_sync_receipt_repository.go +++ b/pkg/datastore/postgres/repositories/header_sync_receipt_repository.go @@ -26,11 +26,11 @@ import ( type HeaderSyncReceiptRepository struct{} func (HeaderSyncReceiptRepository) CreateHeaderSyncReceiptInTx(headerID, transactionID int64, receipt core.Receipt, tx *sqlx.Tx) (int64, error) { - var receiptId int64 - addressId, getAddressErr := repository.GetOrCreateAddressInTransaction(tx, receipt.ContractAddress) + var receiptID int64 + addressID, getAddressErr := repository.GetOrCreateAddressInTransaction(tx, receipt.ContractAddress) if getAddressErr != nil { log.Error("createReceipt: Error getting address id: ", getAddressErr) - return receiptId, getAddressErr + return receiptID, getAddressErr } err := tx.QueryRowx(`INSERT INTO public.header_sync_receipts (header_id, transaction_id, contract_address_id, cumulative_gas_used, gas_used, state_root, status, tx_hash, rlp) @@ -38,10 +38,10 @@ func (HeaderSyncReceiptRepository) CreateHeaderSyncReceiptInTx(headerID, transac ON CONFLICT (header_id, transaction_id) DO UPDATE SET (contract_address_id, cumulative_gas_used, gas_used, state_root, status, tx_hash, rlp) = ($3, $4::NUMERIC, $5::NUMERIC, $6, $7, $8, $9) RETURNING id`, - headerID, transactionID, addressId, receipt.CumulativeGasUsed, receipt.GasUsed, receipt.StateRoot, receipt.Status, receipt.TxHash, receipt.Rlp).Scan(&receiptId) + headerID, transactionID, addressID, receipt.CumulativeGasUsed, receipt.GasUsed, receipt.StateRoot, receipt.Status, receipt.TxHash, receipt.Rlp).Scan(&receiptID) if err != nil { log.Error("header_repository: error inserting receipt: ", err) - return receiptId, err + return receiptID, err } - return receiptId, err + return receiptID, err } diff --git a/pkg/datastore/repository.go b/pkg/datastore/repository.go index 4ea1e293..a9431c81 100644 --- a/pkg/datastore/repository.go +++ b/pkg/datastore/repository.go @@ -57,7 +57,7 @@ type FilterRepository interface { } type FullSyncLogRepository interface { - CreateLogs(logs []core.FullSyncLog, receiptId int64) error + CreateLogs(logs []core.FullSyncLog, receiptID int64) error GetLogs(address string, blockNumber int64) ([]core.FullSyncLog, error) } @@ -74,13 +74,13 @@ type HeaderSyncLogRepository interface { } type FullSyncReceiptRepository interface { - CreateReceiptsAndLogs(blockId int64, receipts []core.Receipt) error - CreateFullSyncReceiptInTx(blockId int64, receipt core.Receipt, tx *sqlx.Tx) (int64, error) + CreateReceiptsAndLogs(blockID int64, receipts []core.Receipt) error + CreateFullSyncReceiptInTx(blockID int64, receipt core.Receipt, tx *sqlx.Tx) (int64, error) GetFullSyncReceipt(txHash string) (core.Receipt, error) } type HeaderSyncReceiptRepository interface { - CreateFullSyncReceiptInTx(blockId int64, receipt core.Receipt, tx *sqlx.Tx) (int64, error) + CreateFullSyncReceiptInTx(blockID int64, receipt core.Receipt, tx *sqlx.Tx) (int64, error) } type WatchedEventRepository interface { diff --git a/pkg/eth/abi.go b/pkg/eth/abi.go index 5b752d75..403a9d70 100644 --- a/pkg/eth/abi.go +++ b/pkg/eth/abi.go @@ -32,7 +32,7 @@ import ( var ( ErrInvalidAbiFile = errors.New("invalid abi") ErrMissingAbiFile = errors.New("missing abi") - ErrApiRequestFailed = errors.New("etherscan api request failed") + ErrAPIRequestFailed = errors.New("etherscan api request failed") ) type Response struct { @@ -72,7 +72,7 @@ func (e *EtherScanAPI) GetAbi(contractHash string) (string, error) { request := fmt.Sprintf("%s/api?module=contract&action=getabi&address=%s", e.url, contractHash) r, err := e.client.Get(request) if err != nil { - return "", ErrApiRequestFailed + return "", ErrAPIRequestFailed } defer r.Body.Close() err = json.NewDecoder(r.Body).Decode(&target) diff --git a/pkg/eth/blockchain.go b/pkg/eth/blockchain.go index 92f5524a..c06b27f4 100644 --- a/pkg/eth/blockchain.go +++ b/pkg/eth/blockchain.go @@ -41,11 +41,11 @@ type BlockChain struct { ethClient core.EthClient headerConverter vulcCommon.HeaderConverter node core.Node - rpcClient core.RpcClient + rpcClient core.RPCClient transactionConverter vulcCommon.TransactionConverter } -func NewBlockChain(ethClient core.EthClient, rpcClient core.RpcClient, node core.Node, converter vulcCommon.TransactionConverter) *BlockChain { +func NewBlockChain(ethClient core.EthClient, rpcClient core.RPCClient, node core.Node, converter vulcCommon.TransactionConverter) *BlockChain { return &BlockChain{ blockConverter: vulcCommon.NewBlockConverter(converter), ethClient: ethClient, @@ -108,7 +108,7 @@ func (blockChain *BlockChain) GetFullSyncLogs(contract core.Contract, startingBl func (blockChain *BlockChain) GetTransactions(transactionHashes []common.Hash) ([]core.TransactionModel, error) { numTransactions := len(transactionHashes) var batch []client.BatchElem - transactions := make([]core.RpcTransaction, numTransactions) + transactions := make([]core.RPCTransaction, numTransactions) for index, transactionHash := range transactionHashes { batchElem := client.BatchElem{ @@ -124,7 +124,7 @@ func (blockChain *BlockChain) GetTransactions(transactionHashes []common.Hash) ( return []core.TransactionModel{}, rpcErr } - return blockChain.transactionConverter.ConvertRpcTransactionsToModels(transactions) + return blockChain.transactionConverter.ConvertRPCTransactionsToModels(transactions) } func (blockChain *BlockChain) LastBlock() (*big.Int, error) { diff --git a/pkg/eth/blockchain_test.go b/pkg/eth/blockchain_test.go index 30ab0a3f..3c2ba916 100644 --- a/pkg/eth/blockchain_test.go +++ b/pkg/eth/blockchain_test.go @@ -37,14 +37,14 @@ var _ = Describe("Geth blockchain", func() { var ( mockClient *fakes.MockEthClient blockChain *eth.BlockChain - mockRpcClient *fakes.MockRpcClient + mockRpcClient *fakes.MockRPCClient mockTransactionConverter *fakes.MockTransactionConverter node vulcCore.Node ) BeforeEach(func() { mockClient = fakes.NewMockEthClient() - mockRpcClient = fakes.NewMockRpcClient() + mockRpcClient = fakes.NewMockRPCClient() mockTransactionConverter = fakes.NewMockTransactionConverter() node = vulcCore.Node{} blockChain = eth.NewBlockChain(mockClient, mockRpcClient, node, mockTransactionConverter) diff --git a/pkg/eth/client/rpc_client.go b/pkg/eth/client/rpc_client.go index 837de9ed..3f3d7753 100644 --- a/pkg/eth/client/rpc_client.go +++ b/pkg/eth/client/rpc_client.go @@ -24,7 +24,7 @@ import ( "github.com/ethereum/go-ethereum/rpc" ) -type RpcClient struct { +type RPCClient struct { client *rpc.Client ipcPath string } @@ -36,14 +36,14 @@ type BatchElem struct { Error error } -func NewRpcClient(client *rpc.Client, ipcPath string) RpcClient { - return RpcClient{ +func NewRPCClient(client *rpc.Client, ipcPath string) RPCClient { + return RPCClient{ client: client, ipcPath: ipcPath, } } -func (client RpcClient) CallContext(ctx context.Context, result interface{}, method string, args ...interface{}) error { +func (client RPCClient) CallContext(ctx context.Context, result interface{}, method string, args ...interface{}) error { //If an empty interface (or other nil object) is passed to CallContext, when the JSONRPC message is created the params will //be interpreted as [null]. This seems to work fine for most of the ethereum clients (which presumably ignore a null parameter. //Ganache however does not ignore it, and throws an 'Incorrect number of arguments' error. @@ -53,15 +53,15 @@ func (client RpcClient) CallContext(ctx context.Context, result interface{}, met return client.client.CallContext(ctx, result, method, args...) } -func (client RpcClient) IpcPath() string { +func (client RPCClient) IpcPath() string { return client.ipcPath } -func (client RpcClient) SupportedModules() (map[string]string, error) { +func (client RPCClient) SupportedModules() (map[string]string, error) { return client.client.SupportedModules() } -func (client RpcClient) BatchCall(batch []BatchElem) error { +func (client RPCClient) BatchCall(batch []BatchElem) error { var rpcBatch []rpc.BatchElem for _, batchElem := range batch { var newBatchElem = rpc.BatchElem{ @@ -78,7 +78,7 @@ func (client RpcClient) BatchCall(batch []BatchElem) error { // Subscribe subscribes to an rpc "namespace_subscribe" subscription with the given channel // The first argument needs to be the method we wish to invoke -func (client RpcClient) Subscribe(namespace string, payloadChan interface{}, args ...interface{}) (*rpc.ClientSubscription, error) { +func (client RPCClient) Subscribe(namespace string, payloadChan interface{}, args ...interface{}) (*rpc.ClientSubscription, error) { chanVal := reflect.ValueOf(payloadChan) if chanVal.Kind() != reflect.Chan || chanVal.Type().ChanDir()&reflect.SendDir == 0 { return nil, errors.New("second argument to Subscribe must be a writable channel") diff --git a/pkg/eth/cold_import/importer.go b/pkg/eth/cold_import/importer.go index 3f1ecf2f..4d5eab77 100644 --- a/pkg/eth/cold_import/importer.go +++ b/pkg/eth/cold_import/importer.go @@ -38,16 +38,16 @@ func NewColdImporter(ethDB ethereum.Database, blockRepository datastore.BlockRep } } -func (ci *ColdImporter) Execute(startingBlockNumber int64, endingBlockNumber int64, nodeId string) error { - missingBlocks := ci.blockRepository.MissingBlockNumbers(startingBlockNumber, endingBlockNumber, nodeId) +func (ci *ColdImporter) Execute(startingBlockNumber int64, endingBlockNumber int64, nodeID string) error { + missingBlocks := ci.blockRepository.MissingBlockNumbers(startingBlockNumber, endingBlockNumber, nodeID) for _, n := range missingBlocks { hash := ci.ethDB.GetBlockHash(n) - blockId, err := ci.createBlocksAndTransactions(hash, n) + blockID, err := ci.createBlocksAndTransactions(hash, n) if err != nil { return err } - err = ci.createReceiptsAndLogs(hash, n, blockId) + err = ci.createReceiptsAndLogs(hash, n, blockID) if err != nil { return err } @@ -65,11 +65,11 @@ func (ci *ColdImporter) createBlocksAndTransactions(hash []byte, i int64) (int64 return ci.blockRepository.CreateOrUpdateBlock(coreBlock) } -func (ci *ColdImporter) createReceiptsAndLogs(hash []byte, number int64, blockId int64) error { +func (ci *ColdImporter) createReceiptsAndLogs(hash []byte, number int64, blockID int64) error { receipts := ci.ethDB.GetBlockReceipts(hash, number) coreReceipts, err := common.ToCoreReceipts(receipts) if err != nil { return err } - return ci.receiptRepository.CreateReceiptsAndLogs(blockId, coreReceipts) + return ci.receiptRepository.CreateReceiptsAndLogs(blockID, coreReceipts) } diff --git a/pkg/eth/cold_import/node_builder.go b/pkg/eth/cold_import/node_builder.go index b9c12080..9ec55bd6 100644 --- a/pkg/eth/cold_import/node_builder.go +++ b/pkg/eth/cold_import/node_builder.go @@ -27,7 +27,7 @@ import ( const ( ColdImportClientName = "LevelDbColdImport" - ColdImportNetworkId float64 = 1 + ColdImportNetworkID float64 = 1 ) var ( @@ -54,15 +54,15 @@ func (cinb ColdImportNodeBuilder) GetNode(genesisBlock []byte, levelPath string) if err != nil { return coldNode, err } - nodeId, err := cinb.parser.ParsePublicKey(string(nodeKey)) + nodeID, err := cinb.parser.ParsePublicKey(string(nodeKey)) if err != nil { return coldNode, err } genesisBlockHash := common.BytesToHash(genesisBlock).String() coldNode = core.Node{ GenesisBlock: genesisBlockHash, - NetworkID: ColdImportNetworkId, - ID: nodeId, + NetworkID: ColdImportNetworkID, + ID: nodeID, ClientName: ColdImportClientName, } return coldNode, nil diff --git a/pkg/eth/cold_import/node_builder_test.go b/pkg/eth/cold_import/node_builder_test.go index 21af752c..3e4db277 100644 --- a/pkg/eth/cold_import/node_builder_test.go +++ b/pkg/eth/cold_import/node_builder_test.go @@ -106,7 +106,7 @@ var _ = Describe("Cold importer node builder", func() { expectedGenesisBlock := common.BytesToHash(fakeGenesisBlock).String() Expect(result.GenesisBlock).To(Equal(expectedGenesisBlock)) Expect(result.ID).To(Equal(fakePublicKeyString)) - Expect(result.NetworkID).To(Equal(cold_import.ColdImportNetworkId)) + Expect(result.NetworkID).To(Equal(cold_import.ColdImportNetworkID)) }) }) diff --git a/pkg/eth/converters/cold_db/transaction_converter.go b/pkg/eth/converters/cold_db/transaction_converter.go index fd6a319e..ebf5e877 100644 --- a/pkg/eth/converters/cold_db/transaction_converter.go +++ b/pkg/eth/converters/cold_db/transaction_converter.go @@ -54,7 +54,7 @@ func (cdtc *ColdDbTransactionConverter) ConvertBlockTransactionsToCore(gethBlock return coreTransactions, nil } -func (cdtc *ColdDbTransactionConverter) ConvertRpcTransactionsToModels(transactions []core.RpcTransaction) ([]core.TransactionModel, error) { +func (cdtc *ColdDbTransactionConverter) ConvertRPCTransactionsToModels(transactions []core.RPCTransaction) ([]core.TransactionModel, error) { panic("converting transaction indexes to integer not supported for cold import") } diff --git a/pkg/eth/converters/common/block_converter_test.go b/pkg/eth/converters/common/block_converter_test.go index 35be0f4c..f7466d64 100644 --- a/pkg/eth/converters/common/block_converter_test.go +++ b/pkg/eth/converters/common/block_converter_test.go @@ -60,7 +60,7 @@ var _ = Describe("Conversion of GethBlock to core.Block", func() { } block := types.NewBlock(&header, []*types.Transaction{}, []*types.Header{}, []*types.Receipt{}) client := fakes.NewMockEthClient() - transactionConverter := rpc.NewRpcTransactionConverter(client) + transactionConverter := rpc.NewRPCTransactionConverter(client) blockConverter := vulcCommon.NewBlockConverter(transactionConverter) coreBlock, err := blockConverter.ToCoreBlock(block) @@ -110,7 +110,7 @@ var _ = Describe("Conversion of GethBlock to core.Block", func() { } uncles := []*types.Header{{Number: big.NewInt(1071817)}, {Number: big.NewInt(1071818)}} block := types.NewBlock(&header, transactions, uncles, []*types.Receipt{&receipt}) - transactionConverter := rpc.NewRpcTransactionConverter(client) + transactionConverter := rpc.NewRPCTransactionConverter(client) blockConverter := vulcCommon.NewBlockConverter(transactionConverter) coreBlock, err := blockConverter.ToCoreBlock(block) @@ -151,7 +151,7 @@ var _ = Describe("Conversion of GethBlock to core.Block", func() { client := fakes.NewMockEthClient() client.SetTransactionReceipts(receipts) - transactionConverter := rpc.NewRpcTransactionConverter(client) + transactionConverter := rpc.NewRPCTransactionConverter(client) blockConverter := vulcCommon.NewBlockConverter(transactionConverter) coreBlock, err := blockConverter.ToCoreBlock(block) @@ -211,7 +211,7 @@ var _ = Describe("Conversion of GethBlock to core.Block", func() { client := fakes.NewMockEthClient() client.SetTransactionReceipts(receipts) - transactionConverter := rpc.NewRpcTransactionConverter(client) + transactionConverter := rpc.NewRPCTransactionConverter(client) blockConverter := vulcCommon.NewBlockConverter(transactionConverter) coreBlock, err := blockConverter.ToCoreBlock(block) @@ -229,7 +229,7 @@ var _ = Describe("Conversion of GethBlock to core.Block", func() { header := types.Header{} block := types.NewBlock(&header, []*types.Transaction{}, []*types.Header{}, []*types.Receipt{}) client := fakes.NewMockEthClient() - transactionConverter := rpc.NewRpcTransactionConverter(client) + transactionConverter := rpc.NewRPCTransactionConverter(client) blockConverter := vulcCommon.NewBlockConverter(transactionConverter) coreBlock, err := blockConverter.ToCoreBlock(block) @@ -270,7 +270,7 @@ var _ = Describe("Conversion of GethBlock to core.Block", func() { []*types.Header{}, []*types.Receipt{gethReceipt}, ) - transactionConverter := rpc.NewRpcTransactionConverter(client) + transactionConverter := rpc.NewRPCTransactionConverter(client) blockConverter := vulcCommon.NewBlockConverter(transactionConverter) coreBlock, err := blockConverter.ToCoreBlock(block) @@ -320,7 +320,7 @@ var _ = Describe("Conversion of GethBlock to core.Block", func() { []*types.Header{}, []*types.Receipt{gethReceipt}, ) - transactionConverter := rpc.NewRpcTransactionConverter(client) + transactionConverter := rpc.NewRPCTransactionConverter(client) blockConverter := vulcCommon.NewBlockConverter(transactionConverter) coreBlock, err := blockConverter.ToCoreBlock(block) @@ -370,7 +370,7 @@ var _ = Describe("Conversion of GethBlock to core.Block", func() { It("returns an error when transaction sender call fails", func() { client := fakes.NewMockEthClient() client.SetTransactionSenderErr(fakes.FakeError) - transactionConverter := rpc.NewRpcTransactionConverter(client) + transactionConverter := rpc.NewRPCTransactionConverter(client) blockConverter := vulcCommon.NewBlockConverter(transactionConverter) _, err := blockConverter.ToCoreBlock(block) @@ -381,7 +381,7 @@ var _ = Describe("Conversion of GethBlock to core.Block", func() { It("returns an error when transaction receipt call fails", func() { client := fakes.NewMockEthClient() client.SetTransactionReceiptErr(fakes.FakeError) - transactionConverter := rpc.NewRpcTransactionConverter(client) + transactionConverter := rpc.NewRPCTransactionConverter(client) blockConverter := vulcCommon.NewBlockConverter(transactionConverter) _, err := blockConverter.ToCoreBlock(block) diff --git a/pkg/eth/converters/common/transaction_converter.go b/pkg/eth/converters/common/transaction_converter.go index fb9584f6..0eb4e5ae 100644 --- a/pkg/eth/converters/common/transaction_converter.go +++ b/pkg/eth/converters/common/transaction_converter.go @@ -23,5 +23,5 @@ import ( type TransactionConverter interface { ConvertBlockTransactionsToCore(gethBlock *types.Block) ([]core.TransactionModel, error) - ConvertRpcTransactionsToModels(transactions []core.RpcTransaction) ([]core.TransactionModel, error) + ConvertRPCTransactionsToModels(transactions []core.RPCTransaction) ([]core.TransactionModel, error) } diff --git a/pkg/eth/converters/rpc/transaction_converter.go b/pkg/eth/converters/rpc/transaction_converter.go index 51f2ffc9..acbb17cb 100644 --- a/pkg/eth/converters/rpc/transaction_converter.go +++ b/pkg/eth/converters/rpc/transaction_converter.go @@ -34,7 +34,7 @@ import ( vulcCommon "github.com/vulcanize/vulcanizedb/pkg/eth/converters/common" ) -type RpcTransactionConverter struct { +type RPCTransactionConverter struct { client core.EthClient } @@ -51,11 +51,11 @@ type transactionData struct { S *big.Int } -func NewRpcTransactionConverter(client core.EthClient) *RpcTransactionConverter { - return &RpcTransactionConverter{client: client} +func NewRPCTransactionConverter(client core.EthClient) *RPCTransactionConverter { + return &RPCTransactionConverter{client: client} } -func (converter *RpcTransactionConverter) ConvertRpcTransactionsToModels(transactions []core.RpcTransaction) ([]core.TransactionModel, error) { +func (converter *RPCTransactionConverter) ConvertRPCTransactionsToModels(transactions []core.RPCTransaction) ([]core.TransactionModel, error) { var results []core.TransactionModel for _, transaction := range transactions { txData, convertErr := getTransactionData(transaction) @@ -88,7 +88,7 @@ func (converter *RpcTransactionConverter) ConvertRpcTransactionsToModels(transac return results, nil } -func (converter *RpcTransactionConverter) ConvertBlockTransactionsToCore(gethBlock *types.Block) ([]core.TransactionModel, error) { +func (converter *RPCTransactionConverter) ConvertBlockTransactionsToCore(gethBlock *types.Block) ([]core.TransactionModel, error) { var g errgroup.Group coreTransactions := make([]core.TransactionModel, len(gethBlock.Transactions())) @@ -122,8 +122,8 @@ func (converter *RpcTransactionConverter) ConvertBlockTransactionsToCore(gethBlo return coreTransactions, nil } -func (rtc *RpcTransactionConverter) appendReceiptToTransaction(transaction core.TransactionModel) (core.TransactionModel, error) { - gethReceipt, err := rtc.client.TransactionReceipt(context.Background(), common.HexToHash(transaction.Hash)) +func (converter *RPCTransactionConverter) appendReceiptToTransaction(transaction core.TransactionModel) (core.TransactionModel, error) { + gethReceipt, err := converter.client.TransactionReceipt(context.Background(), common.HexToHash(transaction.Hash)) if err != nil { return transaction, err } @@ -155,7 +155,7 @@ func convertGethTransactionToModel(transaction *types.Transaction, from *common. }, nil } -func getTransactionData(transaction core.RpcTransaction) (transactionData, error) { +func getTransactionData(transaction core.RPCTransaction) (transactionData, error) { nonce, nonceErr := hexToBigInt(transaction.Nonce) if nonceErr != nil { return transactionData{}, nonceErr diff --git a/pkg/eth/converters/rpc/transaction_converter_test.go b/pkg/eth/converters/rpc/transaction_converter_test.go index d03909b4..930d01c6 100644 --- a/pkg/eth/converters/rpc/transaction_converter_test.go +++ b/pkg/eth/converters/rpc/transaction_converter_test.go @@ -25,16 +25,16 @@ import ( ) var _ = Describe("RPC transaction converter", func() { - var converter rpc.RpcTransactionConverter + var converter rpc.RPCTransactionConverter BeforeEach(func() { - converter = rpc.RpcTransactionConverter{} + converter = rpc.RPCTransactionConverter{} }) It("converts hex fields to integers", func() { rpcTransaction := getFakeRpcTransaction("0x1") - transactionModels, err := converter.ConvertRpcTransactionsToModels([]core.RpcTransaction{rpcTransaction}) + transactionModels, err := converter.ConvertRPCTransactionsToModels([]core.RPCTransaction{rpcTransaction}) Expect(err).NotTo(HaveOccurred()) Expect(len(transactionModels)).To(Equal(1)) @@ -48,7 +48,7 @@ var _ = Describe("RPC transaction converter", func() { It("returns error if invalid hex cannot be converted", func() { invalidTransaction := getFakeRpcTransaction("invalid") - _, err := converter.ConvertRpcTransactionsToModels([]core.RpcTransaction{invalidTransaction}) + _, err := converter.ConvertRPCTransactionsToModels([]core.RPCTransaction{invalidTransaction}) Expect(err).To(HaveOccurred()) }) @@ -56,7 +56,7 @@ var _ = Describe("RPC transaction converter", func() { It("copies RPC transaction hash, from, and to values to model", func() { rpcTransaction := getFakeRpcTransaction("0x1") - transactionModels, err := converter.ConvertRpcTransactionsToModels([]core.RpcTransaction{rpcTransaction}) + transactionModels, err := converter.ConvertRPCTransactionsToModels([]core.RPCTransaction{rpcTransaction}) Expect(err).NotTo(HaveOccurred()) Expect(len(transactionModels)).To(Equal(1)) @@ -67,7 +67,7 @@ var _ = Describe("RPC transaction converter", func() { It("derives transaction RLP", func() { // actual transaction: https://kovan.etherscan.io/tx/0x3b29ef265425d304069c57e5145cd1c7558568b06d231775f50a693bee1aad4f - rpcTransaction := core.RpcTransaction{ + rpcTransaction := core.RPCTransaction{ Nonce: "0x7aa9", GasPrice: "0x3b9aca00", GasLimit: "0x7a120", @@ -82,7 +82,7 @@ var _ = Describe("RPC transaction converter", func() { TransactionIndex: "0xa", } - transactionModels, err := converter.ConvertRpcTransactionsToModels([]core.RpcTransaction{rpcTransaction}) + transactionModels, err := converter.ConvertRPCTransactionsToModels([]core.RPCTransaction{rpcTransaction}) Expect(err).NotTo(HaveOccurred()) Expect(len(transactionModels)).To(Equal(1)) @@ -98,7 +98,7 @@ var _ = Describe("RPC transaction converter", func() { It("does not include transaction receipt", func() { rpcTransaction := getFakeRpcTransaction("0x1") - transactionModels, err := converter.ConvertRpcTransactionsToModels([]core.RpcTransaction{rpcTransaction}) + transactionModels, err := converter.ConvertRPCTransactionsToModels([]core.RPCTransaction{rpcTransaction}) Expect(err).NotTo(HaveOccurred()) Expect(len(transactionModels)).To(Equal(1)) @@ -106,8 +106,8 @@ var _ = Describe("RPC transaction converter", func() { }) }) -func getFakeRpcTransaction(hex string) core.RpcTransaction { - return core.RpcTransaction{ +func getFakeRpcTransaction(hex string) core.RPCTransaction { + return core.RPCTransaction{ Hash: "0x2", Amount: hex, GasLimit: hex, diff --git a/pkg/eth/node/node.go b/pkg/eth/node/node.go index 7fa6a087..90ffb329 100644 --- a/pkg/eth/node/node.go +++ b/pkg/eth/node/node.go @@ -33,12 +33,12 @@ import ( type IPropertiesReader interface { NodeInfo() (id string, name string) - NetworkId() float64 + NetworkID() float64 GenesisBlock() string } type PropertiesReader struct { - client core.RpcClient + client core.RPCClient } type ParityClient struct { @@ -57,18 +57,18 @@ type GanacheClient struct { PropertiesReader } -func MakeNode(rpcClient core.RpcClient) core.Node { +func MakeNode(rpcClient core.RPCClient) core.Node { pr := makePropertiesReader(rpcClient) id, name := pr.NodeInfo() return core.Node{ GenesisBlock: pr.GenesisBlock(), - NetworkID: pr.NetworkId(), + NetworkID: pr.NetworkID(), ID: id, ClientName: name, } } -func makePropertiesReader(client core.RpcClient) IPropertiesReader { +func makePropertiesReader(client core.RPCClient) IPropertiesReader { switch getNodeType(client) { case core.GETH: return GethClient{PropertiesReader: PropertiesReader{client: client}} @@ -83,7 +83,7 @@ func makePropertiesReader(client core.RpcClient) IPropertiesReader { } } -func getNodeType(client core.RpcClient) core.NodeType { +func getNodeType(client core.RPCClient) core.NodeType { if strings.Contains(client.IpcPath(), "infura") { return core.INFURA } @@ -97,14 +97,14 @@ func getNodeType(client core.RpcClient) core.NodeType { return core.PARITY } -func (reader PropertiesReader) NetworkId() float64 { +func (reader PropertiesReader) NetworkID() float64 { var version string err := reader.client.CallContext(context.Background(), &version, "net_version") if err != nil { log.Println(err) } - networkId, _ := strconv.ParseFloat(version, 64) - return networkId + networkID, _ := strconv.ParseFloat(version, 64) + return networkID } func (reader PropertiesReader) GenesisBlock() string { @@ -142,10 +142,10 @@ func (client ParityClient) parityNodeInfo() string { } func (client ParityClient) parityID() string { - var enodeId = regexp.MustCompile(`^enode://(.+)@.+$`) + var enodeID = regexp.MustCompile(`^enode://(.+)@.+$`) var enodeURL string client.client.CallContext(context.Background(), &enodeURL, "parity_enode") - enode := enodeId.FindStringSubmatch(enodeURL) + enode := enodeID.FindStringSubmatch(enodeURL) if len(enode) < 2 { return "" } diff --git a/pkg/eth/node/node_test.go b/pkg/eth/node/node_test.go index ea96670a..e8dcfe9a 100644 --- a/pkg/eth/node/node_test.go +++ b/pkg/eth/node/node_test.go @@ -65,7 +65,7 @@ var _ = Describe("Node Info", func() { }) It("returns parity ID and client name for parity node", func() { - client := fakes.NewMockRpcClient() + client := fakes.NewMockRPCClient() n := node.MakeNode(client) Expect(n.ID).To(Equal("ParityNode")) @@ -74,19 +74,19 @@ var _ = Describe("Node Info", func() { }) It("returns the genesis block for any client", func() { - client := fakes.NewMockRpcClient() + client := fakes.NewMockRPCClient() n := node.MakeNode(client) Expect(n.GenesisBlock).To(Equal(EmpytHeaderHash)) }) It("returns the network id for any client", func() { - client := fakes.NewMockRpcClient() + client := fakes.NewMockRPCClient() n := node.MakeNode(client) Expect(n.NetworkID).To(Equal(float64(1234))) }) It("returns geth ID and client name for geth node", func() { - client := fakes.NewMockRpcClient() + client := fakes.NewMockRPCClient() supportedModules := make(map[string]string) supportedModules["admin"] = "ok" client.SetSupporedModules(supportedModules) @@ -97,7 +97,7 @@ var _ = Describe("Node Info", func() { }) It("returns infura ID and client name for infura node", func() { - client := fakes.NewMockRpcClient() + client := fakes.NewMockRPCClient() client.SetIpcPath("infura/path") n := node.MakeNode(client) Expect(n.ID).To(Equal("infura")) @@ -105,7 +105,7 @@ var _ = Describe("Node Info", func() { }) It("returns local id and client name for Local node", func() { - client := fakes.NewMockRpcClient() + client := fakes.NewMockRPCClient() client.SetIpcPath("127.0.0.1") n := node.MakeNode(client) Expect(n.ID).To(Equal("ganache")) diff --git a/pkg/fakes/mock_block_repository.go b/pkg/fakes/mock_block_repository.go index 70c89d02..79077528 100644 --- a/pkg/fakes/mock_block_repository.go +++ b/pkg/fakes/mock_block_repository.go @@ -31,7 +31,7 @@ type MockBlockRepository struct { createOrUpdateBlockReturnInt int64 missingBlockNumbersCalled bool missingBlockNumbersPassedEndingBlockNumber int64 - missingBlockNumbersPassedNodeId string + missingBlockNumbersPassedNodeID string missingBlockNumbersPassedStartingBlockNumber int64 missingBlockNumbersReturnArray []int64 setBlockStatusCalled bool @@ -48,7 +48,7 @@ func NewMockBlockRepository() *MockBlockRepository { createOrUpdateBlockReturnInt: 0, missingBlockNumbersCalled: false, missingBlockNumbersPassedEndingBlockNumber: 0, - missingBlockNumbersPassedNodeId: "", + missingBlockNumbersPassedNodeID: "", missingBlockNumbersPassedStartingBlockNumber: 0, missingBlockNumbersReturnArray: nil, setBlockStatusCalled: false, @@ -77,11 +77,11 @@ func (repository *MockBlockRepository) GetBlock(blockNumber int64) (core.Block, return core.Block{Number: blockNumber}, nil } -func (repository *MockBlockRepository) MissingBlockNumbers(startingBlockNumber int64, endingBlockNumber int64, nodeId string) []int64 { +func (repository *MockBlockRepository) MissingBlockNumbers(startingBlockNumber int64, endingBlockNumber int64, nodeID string) []int64 { repository.missingBlockNumbersCalled = true repository.missingBlockNumbersPassedStartingBlockNumber = startingBlockNumber repository.missingBlockNumbersPassedEndingBlockNumber = endingBlockNumber - repository.missingBlockNumbersPassedNodeId = nodeId + repository.missingBlockNumbersPassedNodeID = nodeID return repository.missingBlockNumbersReturnArray } @@ -105,11 +105,11 @@ func (repository *MockBlockRepository) AssertCreateOrUpdateBlockCalledWith(block Expect(repository.createOrUpdateBlockPassedBlock).To(Equal(block)) } -func (repository *MockBlockRepository) AssertMissingBlockNumbersCalledWith(startingBlockNumber int64, endingBlockNumber int64, nodeId string) { +func (repository *MockBlockRepository) AssertMissingBlockNumbersCalledWith(startingBlockNumber int64, endingBlockNumber int64, nodeID string) { Expect(repository.missingBlockNumbersCalled).To(BeTrue()) Expect(repository.missingBlockNumbersPassedStartingBlockNumber).To(Equal(startingBlockNumber)) Expect(repository.missingBlockNumbersPassedEndingBlockNumber).To(Equal(endingBlockNumber)) - Expect(repository.missingBlockNumbersPassedNodeId).To(Equal(nodeId)) + Expect(repository.missingBlockNumbersPassedNodeID).To(Equal(nodeID)) } func (repository *MockBlockRepository) AssertSetBlockStatusCalledWith(chainHead int64) { diff --git a/pkg/fakes/mock_blockchain.go b/pkg/fakes/mock_blockchain.go index 53704915..c0f89b8a 100644 --- a/pkg/fakes/mock_blockchain.go +++ b/pkg/fakes/mock_blockchain.go @@ -75,23 +75,23 @@ func (chain *MockBlockChain) SetGetEthLogsWithCustomQueryReturnLogs(logs []types chain.logQueryReturnLogs = logs } -func (blockChain *MockBlockChain) FetchContractData(abiJSON string, address string, method string, methodArgs []interface{}, result interface{}, blockNumber int64) error { - blockChain.fetchContractDataPassedAbi = abiJSON - blockChain.fetchContractDataPassedAddress = address - blockChain.fetchContractDataPassedMethod = method - blockChain.fetchContractDataPassedMethodArgs = methodArgs - blockChain.fetchContractDataPassedResult = result - blockChain.fetchContractDataPassedBlockNumber = blockNumber - return blockChain.fetchContractDataErr +func (chain *MockBlockChain) FetchContractData(abiJSON string, address string, method string, methodArgs []interface{}, result interface{}, blockNumber int64) error { + chain.fetchContractDataPassedAbi = abiJSON + chain.fetchContractDataPassedAddress = address + chain.fetchContractDataPassedMethod = method + chain.fetchContractDataPassedMethodArgs = methodArgs + chain.fetchContractDataPassedResult = result + chain.fetchContractDataPassedBlockNumber = blockNumber + return chain.fetchContractDataErr } func (chain *MockBlockChain) GetBlockByNumber(blockNumber int64) (core.Block, error) { return core.Block{Number: blockNumber}, chain.getBlockByNumberErr } -func (blockChain *MockBlockChain) GetEthLogsWithCustomQuery(query ethereum.FilterQuery) ([]types.Log, error) { - blockChain.logQuery = query - return blockChain.logQueryReturnLogs, blockChain.logQueryErr +func (chain *MockBlockChain) GetEthLogsWithCustomQuery(query ethereum.FilterQuery) ([]types.Log, error) { + chain.logQuery = query + return chain.logQueryReturnLogs, chain.logQueryErr } func (chain *MockBlockChain) GetHeaderByNumber(blockNumber int64) (core.Header, error) { @@ -140,18 +140,18 @@ func (chain *MockBlockChain) AssertFetchContractDataCalledWith(abiJSON string, a Expect(chain.fetchContractDataPassedBlockNumber).To(Equal(blockNumber)) } -func (blockChain *MockBlockChain) AssertGetEthLogsWithCustomQueryCalledWith(query ethereum.FilterQuery) { - Expect(blockChain.logQuery).To(Equal(query)) +func (chain *MockBlockChain) AssertGetEthLogsWithCustomQueryCalledWith(query ethereum.FilterQuery) { + Expect(chain.logQuery).To(Equal(query)) } -func (blockChain *MockBlockChain) SetGetAccountBalanceErr(err error) { - blockChain.getAccountBalanceErr = err +func (chain *MockBlockChain) SetGetAccountBalanceErr(err error) { + chain.getAccountBalanceErr = err } -func (blockChain *MockBlockChain) SetGetAccountBalance(balance *big.Int) { - blockChain.accountBalanceReturnValue = balance +func (chain *MockBlockChain) SetGetAccountBalance(balance *big.Int) { + chain.accountBalanceReturnValue = balance } -func (blockChain *MockBlockChain) GetAccountBalance(address common.Address, blockNumber *big.Int) (*big.Int, error) { - return blockChain.accountBalanceReturnValue, blockChain.getAccountBalanceErr +func (chain *MockBlockChain) GetAccountBalance(address common.Address, blockNumber *big.Int) (*big.Int, error) { + return chain.accountBalanceReturnValue, chain.getAccountBalanceErr } diff --git a/pkg/fakes/mock_parser.go b/pkg/fakes/mock_parser.go index d7a33ebb..03ca5a07 100644 --- a/pkg/fakes/mock_parser.go +++ b/pkg/fakes/mock_parser.go @@ -31,8 +31,8 @@ func (*MockParser) Parse(contractAddr string) error { return nil } -func (m *MockParser) ParseAbiStr(abiStr string) error { - m.AbiToReturn = abiStr +func (parser *MockParser) ParseAbiStr(abiStr string) error { + parser.AbiToReturn = abiStr return nil } diff --git a/pkg/fakes/mock_receipt_repository.go b/pkg/fakes/mock_receipt_repository.go index 80236393..d185cf76 100644 --- a/pkg/fakes/mock_receipt_repository.go +++ b/pkg/fakes/mock_receipt_repository.go @@ -25,7 +25,7 @@ import ( type MockReceiptRepository struct { createReceiptsAndLogsCalled bool - createReceiptsAndLogsPassedBlockId int64 + createReceiptsAndLogsPassedBlockID int64 createReceiptsAndLogsPassedReceipts []core.Receipt createReceiptsAndLogsReturnErr error } @@ -33,7 +33,7 @@ type MockReceiptRepository struct { func NewMockReceiptRepository() *MockReceiptRepository { return &MockReceiptRepository{ createReceiptsAndLogsCalled: false, - createReceiptsAndLogsPassedBlockId: 0, + createReceiptsAndLogsPassedBlockID: 0, createReceiptsAndLogsPassedReceipts: nil, createReceiptsAndLogsReturnErr: nil, } @@ -43,14 +43,14 @@ func (mrr *MockReceiptRepository) SetCreateReceiptsAndLogsReturnErr(err error) { mrr.createReceiptsAndLogsReturnErr = err } -func (mrr *MockReceiptRepository) CreateReceiptsAndLogs(blockId int64, receipts []core.Receipt) error { +func (mrr *MockReceiptRepository) CreateReceiptsAndLogs(blockID int64, receipts []core.Receipt) error { mrr.createReceiptsAndLogsCalled = true - mrr.createReceiptsAndLogsPassedBlockId = blockId + mrr.createReceiptsAndLogsPassedBlockID = blockID mrr.createReceiptsAndLogsPassedReceipts = receipts return mrr.createReceiptsAndLogsReturnErr } -func (mrr *MockReceiptRepository) CreateFullSyncReceiptInTx(blockId int64, receipt core.Receipt, tx *sqlx.Tx) (int64, error) { +func (mrr *MockReceiptRepository) CreateFullSyncReceiptInTx(blockID int64, receipt core.Receipt, tx *sqlx.Tx) (int64, error) { panic("implement me") } @@ -58,9 +58,9 @@ func (mrr *MockReceiptRepository) GetFullSyncReceipt(txHash string) (core.Receip panic("implement me") } -func (mrr *MockReceiptRepository) AssertCreateReceiptsAndLogsCalledWith(blockId int64, receipts []core.Receipt) { +func (mrr *MockReceiptRepository) AssertCreateReceiptsAndLogsCalledWith(blockID int64, receipts []core.Receipt) { Expect(mrr.createReceiptsAndLogsCalled).To(BeTrue()) - Expect(mrr.createReceiptsAndLogsPassedBlockId).To(Equal(blockId)) + Expect(mrr.createReceiptsAndLogsPassedBlockID).To(Equal(blockID)) Expect(mrr.createReceiptsAndLogsPassedReceipts).To(Equal(receipts)) } diff --git a/pkg/fakes/mock_rpc_client.go b/pkg/fakes/mock_rpc_client.go index 67982022..33e453b8 100644 --- a/pkg/fakes/mock_rpc_client.go +++ b/pkg/fakes/mock_rpc_client.go @@ -31,7 +31,7 @@ import ( "github.com/vulcanize/vulcanizedb/pkg/eth/client" ) -type MockRpcClient struct { +type MockRPCClient struct { callContextErr error ipcPath string nodeType core.NodeType @@ -49,7 +49,7 @@ type MockRpcClient struct { supportedModules map[string]string } -func (client *MockRpcClient) Subscribe(namespace string, payloadChan interface{}, args ...interface{}) (*rpc.ClientSubscription, error) { +func (client *MockRPCClient) Subscribe(namespace string, payloadChan interface{}, args ...interface{}) (*rpc.ClientSubscription, error) { client.passedNamespace = namespace passedPayloadChan, ok := payloadChan.(chan statediff.Payload) @@ -66,21 +66,21 @@ func (client *MockRpcClient) Subscribe(namespace string, payloadChan interface{} return &subscription, nil } -func (client *MockRpcClient) AssertSubscribeCalledWith(namespace string, payloadChan chan statediff.Payload, args []interface{}) { +func (client *MockRPCClient) AssertSubscribeCalledWith(namespace string, payloadChan chan statediff.Payload, args []interface{}) { Expect(client.passedNamespace).To(Equal(namespace)) Expect(client.passedPayloadChan).To(Equal(payloadChan)) Expect(client.passedSubscribeArgs).To(Equal(args)) } -func NewMockRpcClient() *MockRpcClient { - return &MockRpcClient{} +func NewMockRPCClient() *MockRPCClient { + return &MockRPCClient{} } -func (client *MockRpcClient) SetIpcPath(ipcPath string) { +func (client *MockRPCClient) SetIpcPath(ipcPath string) { client.ipcPath = ipcPath } -func (client *MockRpcClient) BatchCall(batch []client.BatchElem) error { +func (client *MockRPCClient) BatchCall(batch []client.BatchElem) error { client.passedBatch = batch client.passedMethod = batch[0].Method client.lengthOfBatch = len(batch) @@ -101,7 +101,7 @@ func (client *MockRpcClient) BatchCall(batch []client.BatchElem) error { return nil } -func (client *MockRpcClient) CallContext(ctx context.Context, result interface{}, method string, args ...interface{}) error { +func (client *MockRPCClient) CallContext(ctx context.Context, result interface{}, method string, args ...interface{}) error { client.passedContext = ctx client.passedResult = result client.passedMethod = method @@ -146,41 +146,41 @@ func (client *MockRpcClient) CallContext(ctx context.Context, result interface{} return nil } -func (client *MockRpcClient) IpcPath() string { +func (client *MockRPCClient) IpcPath() string { return client.ipcPath } -func (client *MockRpcClient) SupportedModules() (map[string]string, error) { +func (client *MockRPCClient) SupportedModules() (map[string]string, error) { return client.supportedModules, nil } -func (client *MockRpcClient) SetSupporedModules(supportedModules map[string]string) { +func (client *MockRPCClient) SetSupporedModules(supportedModules map[string]string) { client.supportedModules = supportedModules } -func (client *MockRpcClient) SetCallContextErr(err error) { +func (client *MockRPCClient) SetCallContextErr(err error) { client.callContextErr = err } -func (client *MockRpcClient) SetReturnPOAHeader(header core.POAHeader) { +func (client *MockRPCClient) SetReturnPOAHeader(header core.POAHeader) { client.returnPOAHeader = header } -func (client *MockRpcClient) SetReturnPOWHeaders(headers []*types.Header) { +func (client *MockRPCClient) SetReturnPOWHeaders(headers []*types.Header) { client.returnPOWHeaders = headers } -func (client *MockRpcClient) SetReturnPOAHeaders(headers []core.POAHeader) { +func (client *MockRPCClient) SetReturnPOAHeaders(headers []core.POAHeader) { client.returnPOAHeaders = headers } -func (client *MockRpcClient) AssertCallContextCalledWith(ctx context.Context, result interface{}, method string) { +func (client *MockRPCClient) AssertCallContextCalledWith(ctx context.Context, result interface{}, method string) { Expect(client.passedContext).To(Equal(ctx)) Expect(client.passedResult).To(BeAssignableToTypeOf(result)) Expect(client.passedMethod).To(Equal(method)) } -func (client *MockRpcClient) AssertBatchCalledWith(method string, lengthOfBatch int) { +func (client *MockRPCClient) AssertBatchCalledWith(method string, lengthOfBatch int) { Expect(client.lengthOfBatch).To(Equal(lengthOfBatch)) for _, batch := range client.passedBatch { Expect(batch.Method).To(Equal(method)) diff --git a/pkg/fakes/mock_transaction_converter.go b/pkg/fakes/mock_transaction_converter.go index 5f23310d..4d4f1262 100644 --- a/pkg/fakes/mock_transaction_converter.go +++ b/pkg/fakes/mock_transaction_converter.go @@ -41,7 +41,7 @@ func (converter *MockTransactionConverter) ConvertBlockTransactionsToCore(gethBl return []core.TransactionModel{}, nil } -func (converter *MockTransactionConverter) ConvertRpcTransactionsToModels(transactions []core.RpcTransaction) ([]core.TransactionModel, error) { +func (converter *MockTransactionConverter) ConvertRPCTransactionsToModels(transactions []core.RPCTransaction) ([]core.TransactionModel, error) { converter.ConvertHeaderTransactionIndexToIntCalled = true return nil, nil } diff --git a/test_config/test_config.go b/test_config/test_config.go index 135df08c..eb64c7d4 100644 --- a/test_config/test_config.go +++ b/test_config/test_config.go @@ -120,9 +120,9 @@ func NewTestNode() core.Node { } } -func NewTestBlock(blockNumber int64, repository repositories.BlockRepository) (blockId int64) { - blockId, err := repository.CreateOrUpdateBlock(core.Block{Number: blockNumber}) +func NewTestBlock(blockNumber int64, repository repositories.BlockRepository) int64 { + blockID, err := repository.CreateOrUpdateBlock(core.Block{Number: blockNumber}) Expect(err).NotTo(HaveOccurred()) - return blockId + return blockID } From 4a98b7942f1ccca50d474a6c99ba2e0d9fcb7fc8 Mon Sep 17 00:00:00 2001 From: Rob Mulholand Date: Fri, 18 Oct 2019 12:34:22 -0500 Subject: [PATCH 4/4] Don't return unexported types --- .../shared/helpers/test_helpers/database.go | 8 +++--- .../helpers/test_helpers/mocks/parser.go | 25 +++++++++++-------- .../shared/parser/parser_test.go | 2 +- pkg/plugin/builder/builder.go | 2 +- pkg/plugin/generator.go | 2 +- pkg/plugin/manager/manager.go | 2 +- pkg/plugin/writer/writer.go | 2 +- 7 files changed, 23 insertions(+), 20 deletions(-) diff --git a/pkg/contract_watcher/shared/helpers/test_helpers/database.go b/pkg/contract_watcher/shared/helpers/test_helpers/database.go index d631bc72..66426f46 100644 --- a/pkg/contract_watcher/shared/helpers/test_helpers/database.go +++ b/pkg/contract_watcher/shared/helpers/test_helpers/database.go @@ -159,7 +159,7 @@ func SetupTusdRepo(vulcanizeLogID *int64, wantedEvents, wantedMethods []string) func SetupTusdContract(wantedEvents, wantedMethods []string) *contract.Contract { p := mocks.NewParser(constants.TusdAbiString) - err := p.Parse() + err := p.Parse(constants.TusdContractAddress) Expect(err).ToNot(HaveOccurred()) return contract.Contract{ @@ -205,7 +205,7 @@ func SetupENSRepo(vulcanizeLogID *int64, wantedEvents, wantedMethods []string) ( func SetupENSContract(wantedEvents, wantedMethods []string) *contract.Contract { p := mocks.NewParser(constants.ENSAbiString) - err := p.Parse() + err := p.Parse(constants.EnsContractAddress) Expect(err).ToNot(HaveOccurred()) return contract.Contract{ @@ -223,7 +223,7 @@ func SetupENSContract(wantedEvents, wantedMethods []string) *contract.Contract { func SetupMarketPlaceContract(wantedEvents, wantedMethods []string) *contract.Contract { p := mocks.NewParser(constants.MarketPlaceAbiString) - err := p.Parse() + err := p.Parse(constants.MarketPlaceContractAddress) Expect(err).NotTo(HaveOccurred()) return contract.Contract{ @@ -241,7 +241,7 @@ func SetupMarketPlaceContract(wantedEvents, wantedMethods []string) *contract.Co func SetupMolochContract(wantedEvents, wantedMethods []string) *contract.Contract { p := mocks.NewParser(constants.MolochAbiString) - err := p.Parse() + err := p.Parse(constants.MolochContractAddress) Expect(err).NotTo(HaveOccurred()) return contract.Contract{ diff --git a/pkg/contract_watcher/shared/helpers/test_helpers/mocks/parser.go b/pkg/contract_watcher/shared/helpers/test_helpers/mocks/parser.go index f8784a04..96bc14f6 100644 --- a/pkg/contract_watcher/shared/helpers/test_helpers/mocks/parser.go +++ b/pkg/contract_watcher/shared/helpers/test_helpers/mocks/parser.go @@ -18,7 +18,7 @@ package mocks import ( "github.com/ethereum/go-ethereum/accounts/abi" - + "github.com/vulcanize/vulcanizedb/pkg/contract_watcher/shared/parser" "github.com/vulcanize/vulcanizedb/pkg/contract_watcher/shared/types" "github.com/vulcanize/vulcanizedb/pkg/eth" ) @@ -26,29 +26,32 @@ import ( // Mock parser // Is given ABI string instead of address // Performs all other functions of the real parser -type parser struct { +type mockParser struct { abi string parsedAbi abi.ABI } -func NewParser(abi string) *parser { - - return &parser{ +func NewParser(abi string) parser.Parser { + return &mockParser{ abi: abi, } } -func (p *parser) Abi() string { +func (p *mockParser) Abi() string { return p.abi } -func (p *parser) ParsedAbi() abi.ABI { +func (p *mockParser) ParsedAbi() abi.ABI { return p.parsedAbi } +func (p *mockParser) ParseAbiStr(abiStr string) error { + panic("implement me") +} + // Retrieves and parses the abi string // for the given contract address -func (p *parser) Parse() error { +func (p *mockParser) Parse(contractAddr string) error { var err error p.parsedAbi, err = eth.ParseAbi(p.abi) @@ -58,7 +61,7 @@ func (p *parser) Parse() error { // Returns only specified methods, if they meet the criteria // Returns as array with methods in same order they were specified // Nil wanted array => no events are returned -func (p *parser) GetSelectMethods(wanted []string) []types.Method { +func (p *mockParser) GetSelectMethods(wanted []string) []types.Method { wLen := len(wanted) if wLen == 0 { return nil @@ -78,7 +81,7 @@ func (p *parser) GetSelectMethods(wanted []string) []types.Method { // Returns wanted methods // Empty wanted array => all methods are returned // Nil wanted array => no methods are returned -func (p *parser) GetMethods(wanted []string) []types.Method { +func (p *mockParser) GetMethods(wanted []string) []types.Method { if wanted == nil { return nil } @@ -95,7 +98,7 @@ func (p *parser) GetMethods(wanted []string) []types.Method { // Returns wanted events as map of types.Events // If no events are specified, all events are returned -func (p *parser) GetEvents(wanted []string) map[string]types.Event { +func (p *mockParser) GetEvents(wanted []string) map[string]types.Event { events := map[string]types.Event{} for _, e := range p.parsedAbi.Events { diff --git a/pkg/contract_watcher/shared/parser/parser_test.go b/pkg/contract_watcher/shared/parser/parser_test.go index 3830fbe7..b76c9e15 100644 --- a/pkg/contract_watcher/shared/parser/parser_test.go +++ b/pkg/contract_watcher/shared/parser/parser_test.go @@ -40,7 +40,7 @@ var _ = Describe("Parser", func() { Describe("Mock Parse", func() { It("Uses parses given abi string", func() { mp := mocks.NewParser(constants.DaiAbiString) - err = mp.Parse() + err = mp.Parse(constants.DaiContractAddress) Expect(err).ToNot(HaveOccurred()) parsedAbi := mp.ParsedAbi() diff --git a/pkg/plugin/builder/builder.go b/pkg/plugin/builder/builder.go index d6de5ba5..d045dff5 100644 --- a/pkg/plugin/builder/builder.go +++ b/pkg/plugin/builder/builder.go @@ -42,7 +42,7 @@ type builder struct { } // Requires populated plugin config -func NewPluginBuilder(gc config.Plugin) *builder { +func NewPluginBuilder(gc config.Plugin) PluginBuilder { return &builder{ GenConfig: gc, tmpVenDirs: make([]string, 0), diff --git a/pkg/plugin/generator.go b/pkg/plugin/generator.go index 7b3310f2..d0038ee7 100644 --- a/pkg/plugin/generator.go +++ b/pkg/plugin/generator.go @@ -36,7 +36,7 @@ type generator struct { } // Creates a new generator from a plugin and database config -func NewGenerator(gc config.Plugin, dbc config.Database) (*generator, error) { +func NewGenerator(gc config.Plugin, dbc config.Database) (Generator, error) { if len(gc.Transformers) < 1 { return nil, errors.New("plugin generator is not configured with any transformers") } diff --git a/pkg/plugin/manager/manager.go b/pkg/plugin/manager/manager.go index 0b96c764..a1a0abe8 100644 --- a/pkg/plugin/manager/manager.go +++ b/pkg/plugin/manager/manager.go @@ -41,7 +41,7 @@ type manager struct { } // Manager requires both filled in generator and database configs -func NewMigrationManager(gc config.Plugin, dbc config.Database) *manager { +func NewMigrationManager(gc config.Plugin, dbc config.Database) MigrationManager { return &manager{ GenConfig: gc, DBConfig: dbc, diff --git a/pkg/plugin/writer/writer.go b/pkg/plugin/writer/writer.go index 3cc1a71d..e56a477d 100644 --- a/pkg/plugin/writer/writer.go +++ b/pkg/plugin/writer/writer.go @@ -37,7 +37,7 @@ type writer struct { } // Requires populated plugin config -func NewPluginWriter(gc config.Plugin) *writer { +func NewPluginWriter(gc config.Plugin) PluginWriter { return &writer{ GenConfig: gc, }