Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Firehose #7

Merged
merged 45 commits into from
Oct 23, 2024
Merged

Firehose #7

merged 45 commits into from
Oct 23, 2024

Conversation

Eduard-Voiculescu
Copy link
Collaborator

@Eduard-Voiculescu Eduard-Voiculescu commented Oct 4, 2024

Closes: #XXX

Description


For contributor use:

  • Targeted PR against correct branch (see CONTRIBUTING.md)
  • Linked to Github issue with discussion and accepted design OR link to spec that describes this work.
  • Code follows the module structure standards.
  • Wrote unit and integration tests
  • Updated relevant documentation (docs/) or specification (x/<module>/spec/)
  • Added relevant godoc comments.
  • Added a relevant changelog entry to the Unreleased section in CHANGELOG.md
  • Re-reviewed Files changed in the Github PR explorer

For admin use:

  • Added appropriate labels to PR (ex. WIP, R4R, docs, etc)
  • Reviewers assigned
  • Squashed all commits, uses message "Merge pull request #XYZ: [title]" (coding standards)

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced enhanced tracing capabilities for Ethereum transactions using the Firehose protocol.
    • Added new tracing hooks for block and transaction events, improving observability.
    • Expanded the .gitignore to include environment files.
    • Implemented new functions for managing Ethereum block events within the Cosmos SDK.
    • Updated EVM configuration to support additional tracer types, including "firehose."
    • Added a new error handling mechanism for state overrides.
  • Bug Fixes

    • Improved error handling for invalid trace configurations in tests.
  • Documentation

    • Updated configuration templates to include new tracer types.
  • Tests

    • Added new test cases to validate tracing functionalities and enhance coverage for state transitions and balance changes.
  • Chores

    • Updated dependency versions for improved compatibility and performance.

arrivets and others added 9 commits September 30, 2024 09:29
This breaks some tests and shows that we need to add calls to OnBlockStart to
prevent panics.
- move some files around to keep them contained inside of the x/evm package
- adding env file ignore in gitignore
- Removing tracer from the EthermintApp struct
- Updating tests which referenced the tracer from the EVMKeeper
- Adding InitChainer method on keeper to call when a block chain is initialized
@Eduard-Voiculescu Eduard-Voiculescu marked this pull request as draft October 4, 2024 17:18
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 19

🧹 Outside diff range and nitpick comments (25)
pb/sf/ethereum/type/v2/type.go (2)

9-9: Consider using a more descriptive name and making it a constant.

The variable b0 is not very descriptive. Consider renaming it to something more meaningful, like zeroBI or zeroBigInt. Additionally, since this value never changes, it would be better to declare it as a constant.

Here's a suggested improvement:

-var b0 = big.NewInt(0)
+const zeroBigInt = new(big.Int)

Note: new(big.Int) creates a new *big.Int initialized to zero, which is equivalent to big.NewInt(0).


15-17: LGTM: Time method is well-implemented. Consider a small optimization.

The Time method for the Block type is correctly implemented. It returns the block's timestamp as a time.Time object, which is useful for time-based operations and formatting.

For a small optimization, you could consider returning the result directly:

func (b *Block) Time() time.Time {
-	return b.Header.Timestamp.AsTime()
+	return b.Header.Timestamp.AsTime()
}

This avoids creating an unnecessary temporary variable.

x/evm/keeper/msg_server_test.go (2)

Line range hint 26-93: Consider enhancing test coverage

The TestEthereumTx function is well-structured and uses table-driven tests effectively. However, consider the following suggestions to further improve the test coverage:

  1. Add more test cases to cover different transaction types and edge cases.
  2. Include assertions to verify the state changes after successful transactions (e.g., balance changes, contract deployment).
  3. Test with different gas prices and limits to ensure correct gas calculations.
  4. Consider adding a test case for transactions with access lists to fully test the ethtypes.AccessListTxType.

Would you like assistance in implementing these improvements?


Line range hint 95-127: Enhance TestUpdateParams function

The TestUpdateParams function is well-structured and covers basic scenarios. To improve its effectiveness, consider the following suggestions:

  1. Add more test cases with different parameter values to ensure all aspects of the params are tested.
  2. Include assertions to verify that the params are actually updated after a successful call.
  3. Test the behavior when updating individual params instead of the entire params object.
  4. Consider adding a test case for updating params with invalid values to ensure proper validation.

Would you like assistance in implementing these improvements?

server/config/config.go (1)

109-109: Summary: New "firehose" EVM tracer added

The addition of the "firehose" tracer type to the evmTracers slice is a minor change that expands the available EVM tracing options. This change appears to be safe and doesn't introduce any obvious issues in this file.

To ensure completeness:

  1. Verify that the implementation of the "firehose" tracer exists in the codebase (as suggested in the previous comment).
  2. Update any relevant documentation or user guides to include information about this new tracer option.
  3. Consider adding a brief comment in the code explaining the purpose or use case for the "firehose" tracer, if appropriate.
x/evm/handler_test.go (1)

Line range hint 107-111: Investigate potential mismatch in error description

The comment suggests that the error description "insufficient balance" might be inaccurate, and "insufficient gas" could be more appropriate. This distinction is important for proper error handling and user feedback.

Consider investigating this test case further to ensure the error description accurately reflects the underlying issue. If confirmed, update the error message in the relevant part of the codebase.

x/evm/keeper/abci.go (1)

58-62: Simplify deferred function call in EndBlock

The deferred anonymous function wrapping k.evmTracer.OnBlockEnd(nil) adds unnecessary complexity. You can simplify the code by deferring the call directly, which enhances readability.

Apply this diff to simplify the code:

-if k.evmTracer != nil && k.evmTracer.OnBlockEnd != nil {
-    defer func() {
-        k.evmTracer.OnBlockEnd(nil)
-    }()
+if k.evmTracer != nil && k.evmTracer.OnBlockEnd != nil {
+    defer k.evmTracer.OnBlockEnd(nil)
 }
x/evm/keeper/keeper.go (1)

69-70: Provide a more detailed comment for evmTracer field

The comment // EVM Tracer is brief. To improve code readability and maintainability, consider adding a more descriptive comment explaining the purpose and usage of the evmTracer field.

For example:

// evmTracer is used for EVM transaction tracing and debugging purposes.
evmTracer *tracers.Tracer
x/evm/tracers/firehose_test.go (4)

39-39: Typo in test case name 'emtpy'

There's a typo in the test case name: "push/pop emtpy" should be "push/pop empty".

Apply this diff to correct the typo:

-"push/pop emtpy", []actionRunner{
+"push/pop empty", []actionRunner{

85-86: Correct typo in test case name 'inexistant'

The test case name "inexistant" is misspelled. It should be "inexistent" or "nonexistent".

Apply this diff to correct the typo:

-{"inexistant", 255, false, nil},
+{"inexistent", 255, false, nil},

150-150: Typo in comment: 'codde' should be 'code'

In the comment at line 150, there's a typo: "codde" should be "code".

Apply this diff to correct the typo:

-// the expected fields of `types.Header` changed
-// that the expected fields of `types.Header` changed
+// the expected fields of `types.Header` changed.
+// that the expected fields of `types.Header` changed.

355-355: Typo in error message: 'intial' should be 'initial'

In the error message at line 355, "intial" should be "initial".

Apply this diff to correct the typo:

-t.Fatalf("the golden file %q does not exist, re-run with 'GOLDEN_UPDATE=true go test ./... -run %q' to generate the intial version", goldenPath, t.Name())
+t.Fatalf("the golden file %q does not exist, re-run with 'GOLDEN_UPDATE=true go test ./... -run %q' to generate the initial version", goldenPath, t.Name())
x/evm/keeper/state_transition.go (1)

484-488: Add tests to ensure OnGasChange is not called multiple times

The TODO comment indicates a need to test that k.evmTracer.OnGasChange is not called multiple times. This is important to prevent inconsistencies in gas tracking and potential performance issues.

Would you like assistance in generating unit tests to verify that OnGasChange is called exactly once per transaction? I can help create a test case to ensure the tracer behaves as expected.

x/evm/statedb/statedb.go (4)

103-104: Add GoDoc comment for evmTracer field

The evmTracer field is an important addition to the StateDB struct for tracing EVM operations. To maintain code clarity and adhere to Go documentation standards, please add a GoDoc comment explaining its purpose.

Apply this diff to include the comment:

 type StateDB struct {
     keeper Keeper
+    // evmTracer is used to facilitate tracing of EVM operations.
     evmTracer *tracing.Hooks
     // handle balances natively
     evmDenom string
     err      error
 }

149-151: Add GoDoc comment for SetTracer method

The SetTracer method is an exported function that allows setting the EVM tracer. Please add a GoDoc comment to explain its functionality and maintain documentation consistency.

Apply this diff to include the comment:

+// SetTracer sets the EVM tracer for the StateDB.
 func (s *StateDB) SetTracer(tracer *tracing.Hooks) {
     s.evmTracer = tracer
 }

548-553: Remove unnecessary TODO comment in SetStorage

The comment // TODO: should we call a tracer hook here? is unnecessary if a decision has been made. If tracing is not required here, consider removing the comment to keep the code clean.


389-389: Correct grammatical error in comment

There's a minor grammatical error in the comment. The word "fail" should be "fails" to match the singular verb form.

Apply this diff to fix the comment:

 // ExecuteNativeAction executes native action in isolate,
-// the writes will be reverted when either the native action itself fail
+// the writes will be reverted when either the native action itself fails
 // or the wrapping message call reverted.
x/evm/statedb/statedb_test.go (1)

52-53: Address the TODO: Add tests with the Tracer

There's a TODO comment indicating that tests need to be added for the Tracer functionality. Implementing these tests will enhance test coverage and ensure the Tracer works as expected.

Would you like assistance in creating these tests or opening a GitHub issue to track this task?

x/evm/keeper/grpc_query_test.go (3)

Line range hint 1046-1050: Ensure full response validation in test assertions

Slicing res.Data to the first 150 characters may cause the test to miss critical differences in the response beyond this point. This could lead to false positives where discrepancies are not detected. Consider comparing the full res.Data or using a method that focuses on the essential parts of the response relevant to the test case.


1203-1204: Define large numeric literals as constants for clarity

The hardcoded value 1000000000000000000 may reduce readability and make the code harder to maintain. Consider defining this value as a constant with a descriptive name to enhance clarity.

Apply this change:

+	const testBalance = 1000000000000000000
+	err := suite.App.EvmKeeper.SetBalance(suite.Ctx, suite.Address, big.NewInt(testBalance), types.DefaultEVMDenom)
-	err := suite.App.EvmKeeper.SetBalance(suite.Ctx, suite.Address, big.NewInt(1000000000000000000), types.DefaultEVMDenom)

Line range hint 1224-1228: Use comprehensive assertion methods for larger responses

By slicing res.Data to 150 characters, the test might not detect important differences in the remainder of the data. This could cause the test to pass when it should fail. It's better to use assertions that check the entire response or key elements that are critical to the test's purpose.

app/app.go (1)

1117-1150: Address the TODO comments in TmBlockHeaderToEVM

The function TmBlockHeaderToEVM contains several // todo comments indicating incomplete implementations or areas requiring verification. Specifically, the fields Nonce, MixDigest, UncleHash, Bloom, Difficulty, Extra, and BaseFee have placeholder values or comments suggesting further action. Before merging, please address these TODOs to ensure the function is fully implemented and accurate. If certain fields are not applicable to Injective, consider providing explanations or removing them to avoid confusion.

Would you like assistance in implementing these fields or creating GitHub issues to track these tasks?

x/evm/tracers/firehose.go (3)

1751-1752: Nitpick: Grammatical error in panic message

In the gasChangeReasonFromChain function, there's a grammatical error in the panic message:

  • "check vm.GasChangeReason so see to which constant it refers to" should be "check vm.GasChangeReason to see which constant it refers to".

Apply the following diff to correct the message:

-panic(fmt.Errorf("unknown tracer gas change reason value '%d', check vm.GasChangeReason so see to which constant it refers to", reason))
+panic(fmt.Errorf("unknown tracer gas change reason value '%d', check vm.GasChangeReason to see which constant it refers to", reason))

2096-2097: Nitpick: Regular expression pattern may need clarification

In the declaration of sanitizeRegexp, the regular expression pattern [\t( ){2,}]+ might be unclear to future maintainers. It's helpful to add a comment explaining the purpose of this pattern for better readability.

Consider adding a comment to explain the regular expression:

var sanitizeRegexp = regexp.MustCompile(`[\t( ){2,}]+`) // Removes multiple spaces and tabs

976-985: Issue: Commented-out code in getExecutedCode function

There is a block of commented-out code in the getExecutedCode function. Keeping outdated or dead code can clutter the codebase and make maintenance harder.

Consider removing the commented-out code if it's no longer needed, or explain why it's kept.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 7a7579f and 5376e54.

⛔ Files ignored due to path filters (2)
  • go.sum is excluded by !**/*.sum
  • pb/sf/ethereum/type/v2/type.pb.go is excluded by !**/*.pb.go
📒 Files selected for processing (23)
  • .gitignore (1 hunks)
  • app/app.go (4 hunks)
  • go.mod (6 hunks)
  • pb/sf/ethereum/type/v2/type.go (1 hunks)
  • server/config/config.go (1 hunks)
  • server/config/toml.go (1 hunks)
  • x/evm/genesis.go (1 hunks)
  • x/evm/handler_test.go (2 hunks)
  • x/evm/keeper/abci.go (3 hunks)
  • x/evm/keeper/config.go (2 hunks)
  • x/evm/keeper/grpc_query_test.go (3 hunks)
  • x/evm/keeper/integration_test.go (2 hunks)
  • x/evm/keeper/keeper.go (4 hunks)
  • x/evm/keeper/msg_server_test.go (1 hunks)
  • x/evm/keeper/state_transition.go (7 hunks)
  • x/evm/keeper/state_transition_test.go (4 hunks)
  • x/evm/statedb/statedb.go (5 hunks)
  • x/evm/statedb/statedb_test.go (1 hunks)
  • x/evm/tracers/firehose.go (1 hunks)
  • x/evm/tracers/firehose_test.go (1 hunks)
  • x/evm/tracers/testdata/firehose/reorder-ordinals-empty.golden.json (1 hunks)
  • x/evm/types/tracer.go (4 hunks)
  • x/evm/types/utils.go (1 hunks)
✅ Files skipped from review due to trivial changes (3)
  • .gitignore
  • x/evm/genesis.go
  • x/evm/types/utils.go
🔇 Additional comments (42)
pb/sf/ethereum/type/v2/type.go (3)

1-7: LGTM: Package declaration and imports are appropriate.

The package name pbeth is concise and descriptive. The imported packages are relevant to the implemented functionalities, and there are no unused imports.


11-13: LGTM: PreviousID method is well-implemented.

The PreviousID method for the Block type is correctly implemented. It returns the parent block's hash as a hexadecimal string, which is a common representation in Ethereum. The method name is clear and descriptive.


19-27: 🛠️ Refactor suggestion

Consider a more descriptive method name and potential performance optimization.

The Native method for the BigInt type is implemented correctly, but there are a few points to consider:

  1. The method name Native is not very descriptive. Consider renaming it to something like ToBigInt or AsBigInt to better reflect its purpose.

  2. The nil check is a good practice for avoiding panics.

  3. The method creates a new big.Int for each call, which could be inefficient if called frequently. If this method is called often, you might want to consider caching the result.

Here's a suggested improvement:

func (m *BigInt) ToBigInt() *big.Int {
	if m == nil {
		return zeroBigInt
	}
	if m.bigInt == nil {
		m.bigInt = new(big.Int).SetBytes(m.Bytes)
	}
	return m.bigInt
}

This implementation caches the big.Int value, reducing allocations for repeated calls. Note that this assumes you add a bigInt *big.Int field to your BigInt struct.

To assess the impact of this change, we should check how frequently this method is called in the codebase. Here's a script to help with that:

Please review the results of this script to determine if the optimization is necessary.

✅ Verification successful

Verified: The Native method is only defined and not invoked elsewhere.

The performance optimization suggestion is not necessary at this time since there are no external calls to Native. However, renaming the method to ToBigInt or AsBigInt is still recommended for improved clarity.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for calls to the Native method on BigInt
rg --type go 'BigInt.*Native\(\)'

Length of output: 103

x/evm/keeper/msg_server_test.go (3)

81-81: Improved code readability

The addition of this empty line enhances the readability of the test case by clearly separating the setup phase (tc.malleate()) from the execution phase. This is a good practice in test writing.


87-87: Enhanced test structure

The addition of this empty line improves the test structure by clearly separating the error handling block from the subsequent assertions. This enhances the readability and maintainability of the test case.


Line range hint 1-127: Overall assessment: Good changes with room for improvement

The changes to this file improve the readability and organization of the test suite. The use of table-driven tests and clear separation of test phases are commendable. However, there are opportunities to enhance the test coverage and assertions in both TestEthereumTx and TestUpdateParams functions.

Consider implementing the suggested improvements to make the test suite more robust and comprehensive. This will help ensure the reliability and correctness of the EVM keeper's message server implementation.

x/evm/keeper/integration_test.go (2)

4-4: LGTM: New import added correctly

The new import for srvflags is correctly added and necessary for using srvflags.EVMTracer in the setupTest function.


140-143: LGTM: EVM Tracer configuration added to test setup

The addition of srvflags.EVMTracer with the value evmtypes.Firehose enhances the test setup by configuring the EVM tracer for integration tests. This change is consistent with the new import and the overall purpose of the integration tests.

To ensure this change doesn't have unintended consequences, please verify:

  1. That the Firehose tracer is properly initialized and used in the relevant EVM transaction processing code.
  2. That this change doesn't affect other test suites or require additional configuration changes elsewhere in the codebase.

You can use the following script to check for other occurrences of EVM tracer configuration:

✅ Verification successful

Verified: No Additional EVM Tracer Configurations Found

The verification confirms that the srvflags.EVMTracer: evmtypes.Firehose configuration is only present in x/evm/keeper/integration_test.go. There are no other occurrences in the codebase, ensuring that this change is isolated to the test setup and does not impact other areas.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other occurrences of EVM tracer configuration
rg --type go 'EVMTracer.*Firehose'

Length of output: 116

x/evm/tracers/testdata/firehose/reorder-ordinals-empty.golden.json (5)

1-23: Block header structure looks good.

The block header section is well-structured and contains all the necessary fields for a blockchain block. The use of placeholder values (e.g., for parentHash and stateRoot) is appropriate for a test fixture.


24-55: Transaction trace structure is correct with proper ordinal sequencing.

The first transaction trace is well-structured and includes all necessary fields. The beginOrdinal and endOrdinal fields are correctly implemented, providing a clear sequence of events within the transaction. This is crucial for the Firehose system to maintain the correct order of operations.


120-122: Version field is correctly specified.

The ver field is properly set to 4, which indicates the version of the data format used in this file. This is important for maintaining compatibility and interpreting the data correctly.


1-122: Well-structured test fixture for Firehose ordinal reordering.

This JSON file serves as a comprehensive test fixture for the Firehose system, specifically focusing on the reordering of ordinals across multiple transactions and their associated calls. The file structure accurately represents a blockchain block with detailed transaction traces.

Key points:

  1. The block header contains all necessary fields with appropriate placeholder values.
  2. Transaction traces are well-structured with correct ordinal sequencing.
  3. The beginOrdinal and endOrdinal fields provide a clear sequence of events across all transactions and calls.
  4. The version field (ver: 4) is correctly specified.

This fixture will be valuable for testing the Firehose system's ability to maintain the correct order of operations when processing blockchain data.


56-119: Transaction traces maintain consistency with proper ordinal sequencing.

The second and third transaction traces maintain the correct structure and ordinal sequencing. The beginOrdinal and endOrdinal fields continue sequentially across all transactions, which is crucial for the Firehose system's reordering functionality.

Note: The index field is present in the second and third transactions but missing in the first one. While this might be intentional for testing purposes, it's worth confirming if this inconsistency is expected.

To verify the consistency of the index field across all transactions in the codebase, you can run the following script:

✅ Verification successful

All transaction traces include the index field consistently.

All transaction traces in x/evm/tracers/testdata/firehose/reorder-ordinals-empty.golden.json contain the index field, ensuring uniformity across all transactions.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for consistency of the 'index' field in transaction traces

# Test: Search for transaction traces and check if they all have the 'index' field
rg --type json '"transactionTraces"' -A 20 | rg '"index":'

Length of output: 60


Script:

#!/bin/bash
# Description: Verify that all transaction traces have an 'index' field

# Search for all occurrences of 'transactionTraces' and check for the presence of 'index' within them
rg --type json '"transactionTraces"' -A 50 | rg '"index":' || echo "No inconsistencies found: All transaction traces have the 'index' field."

Length of output: 234

server/config/toml.go (1)

28-28: LGTM. Verify implementation of the new tracer type.

The addition of 'firehose' as a valid tracer type is approved. This expands the options available for the EVM tracer configuration.

To ensure this change is fully implemented, please run the following verification:

Please ensure that the 'firehose' tracer type is properly implemented in the EVM code and that any necessary documentation has been updated.

✅ Verification successful

Verified: 'firehose' tracer type is properly implemented.

The firehose tracer type has been successfully integrated into the codebase, as evidenced by its presence in multiple implementation and configuration files.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the implementation of the 'firehose' tracer type

# Test 1: Check if 'firehose' is handled in the tracer implementation
echo "Checking for 'firehose' in tracer implementation:"
rg --type go -i 'case\s+["\']firehose["\']\s*:'

# Test 2: Look for any new files or functions related to 'firehose' tracer
echo "Searching for 'firehose' related files or functions:"
rg --type go -i 'firehose'

# Test 3: Check for updates in documentation or comments related to tracers
echo "Checking for updates in documentation or comments:"
rg --type go -i 'tracer.*firehose'

Length of output: 209


Script:

#!/bin/bash
# Description: Verify the implementation of the 'firehose' tracer type

# Test 1: Check if 'firehose' is handled in the tracer implementation
echo "Checking for 'firehose' in tracer implementation:"
rg --type go -i 'case\s+["'"'"']firehose["'"'"']\s*:'

# Test 2: Look for any new files or functions related to 'firehose' tracer
echo "Searching for 'firehose' related files or functions:"
rg --type go -i 'firehose'

# Test 3: Check for updates in documentation or comments related to tracers
echo "Checking for updates in documentation or comments:"
rg --type go -i 'tracer.*firehose'

Length of output: 24040

server/config/config.go (2)

109-109: Verify implementation of the "firehose" tracer

While adding the new "firehose" tracer type to the evmTracers slice is straightforward, it's important to ensure that the implementation for this tracer type exists in the codebase.

Let's check for the implementation of the "firehose" tracer:

#!/bin/bash
# Search for the implementation of the "firehose" tracer
rg --type go "func.*firehose.*Tracer"

If the implementation is not found, please ensure that it's added in the appropriate location before merging this change.


109-109: New EVM tracer type added: "firehose"

The evmTracers slice has been updated to include a new tracer type "firehose". This addition expands the available options for EVM tracing.

To ensure this change is properly integrated, let's verify if any other parts of the code need to be updated:

✅ Verification successful

Firehose tracer type is properly integrated

The new tracer type "firehose" has been added to the evmTracers slice and is consistently used in other parts of the codebase, including firehose.go and relevant test files. No further updates are necessary.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if the new tracer type is used or validated elsewhere in the codebase
rg --type go "firehose.*tracer" --ignore-file server/config/config.go

Length of output: 133


Script:

#!/bin/bash
# Check if the new tracer type "firehose" is used or validated elsewhere in the codebase
rg --type go 'firehose.*tracer' --ignore-file server/config/config.go

Length of output: 9196


Script:

#!/bin/bash
# Check if the new tracer type "firehose" is used or validated elsewhere in the codebase
rg --type go 'firehose.*tracer' -g '!server/config/config.go'

Length of output: 557

x/evm/keeper/abci.go (1)

34-47: Verify the correctness of the total difficulty (TD) value

The TD (total difficulty) is set to big.NewInt(1). Ensure that this value accurately reflects the actual total difficulty of the blockchain at the current block height. An incorrect TD value may lead to inconsistencies in tracing and downstream processes.

Run the following script to check the total difficulty value:

This script fetches the total difficulty of the latest block from the local Ethereum node. Compare this value with the one set in the code to ensure consistency.

x/evm/types/tracer.go (1)

75-84: NewLiveTracer function is correctly implemented with error handling

The new NewLiveTracer function properly initializes live tracers and includes appropriate error handling. This ensures that any issues during tracer initialization are caught and reported.

x/evm/keeper/config.go (2)

158-167: LGTM: Conditional Tracer assignment is correctly implemented

The updated code in the VMConfig method correctly assigns the Tracer field of vmCfg based on the presence of cfg.Tracer and its Hooks. The conditional checks prevent nil pointer dereferences and ensure proper tracer configuration.


134-136: ⚠️ Potential issue

Ensure thread safety when accessing k.evmTracer

Accessing k.evmTracer without synchronization may lead to data races if k.evmTracer is modified concurrently by other goroutines. Please confirm that k.evmTracer is immutable after initialization or properly synchronized to prevent concurrency issues.

Consider verifying that k.evmTracer is only set during initialization and not modified thereafter. You can run the following script to search for assignments to k.evmTracer:

✅ Verification successful

Thread Safety of k.evmTracer Verified

The assignment to k.evmTracer is only done during initialization in x/evm/keeper/keeper.go. There are no other assignments, ensuring that k.evmTracer remains immutable after initialization.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find all assignments to k.evmTracer to ensure it is not modified concurrently.

# Test: Search for assignments to k.evmTracer. Expect: Should only find assignments during initialization.
rg --type go 'k\.evmTracer\s*='

Length of output: 78

x/evm/keeper/keeper.go (2)

142-146: Initialize the EVM tracer safely in InitChainer

The new InitChainer method appropriately initializes the EVM tracer if it's set. Ensure that this method is called during the module's initialization phase to correctly set up tracing.


Line range hint 98-118: Verify all calls to NewKeeper are updated to the new signature

The NewKeeper function signature has been changed by removing the tracer parameter. Ensure that all instantiations of NewKeeper in the codebase are updated to reflect this change to prevent build errors or unexpected behavior.

Run the following script to find any calls to NewKeeper that still use the old signature with the tracer parameter:

This script searches for any instances where NewKeeper is called with a tracer parameter. If any matches are found, they need to be updated to align with the new function signature.

go.mod (7)

99-99: Approved: Addition of indirect dependency github.com/chenzhuoyu/iasm

The addition of github.com/chenzhuoyu/iasm as an indirect dependency is acceptable.


192-193: Approved: Addition of indirect dependencies

The additions of github.com/klauspost/cpuid/v2 and github.com/knz/go-libedit as indirect dependencies are acceptable.


213-213: Approved: Update of github.com/pelletier/go-toml/v2 dependency

Updating github.com/pelletier/go-toml/v2 to version v2.2.3 is acceptable.


256-256: Approved: Update of golang.org/x/crypto dependency

Updating golang.org/x/crypto to version v0.27.0 is acceptable.


258-259: Approved: Updates of golang.org/x/sys and golang.org/x/term dependencies

Updating golang.org/x/sys to version v0.25.0 and golang.org/x/term to version v0.24.0 is acceptable.


53-56: ⚠️ Potential issue

Caution: Usage of golang.org/x/exp introduces unstable APIs

The golang.org/x/exp package contains experimental code, and its APIs are unstable and subject to change without notice. Including this dependency might introduce instability into the codebase. Please verify whether this dependency is necessary and consider using stable alternatives if possible.

Run the following script to identify where golang.org/x/exp is used in the codebase:


284-284: Verify compatibility when replacing nhooyr.io/websocket with github.com/coder/websocket

Replacing nhooyr.io/websocket with github.com/coder/websocket may introduce compatibility issues if the APIs differ. Please ensure that all usages of nhooyr.io/websocket in the codebase are compatible with github.com/coder/websocket.

Run the following script to check for usages of nhooyr.io/websocket and assess compatibility:

✅ Verification successful

Compatibility Verified for WebSocket Replacement

No usages of nhooyr.io/websocket were found in the codebase. Replacing it with github.com/coder/websocket does not introduce compatibility issues.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find all imports of 'nhooyr.io/websocket' in the codebase.

# Test: Search for import statements of 'nhooyr.io/websocket'. Expect: Verify that replacements are compatible.
rg --type go '^import.*"nhooyr\.io/websocket' -A 5

Length of output: 52


Script:

#!/bin/bash
# Description: Use ast-grep to find all import declarations of 'nhooyr.io/websocket' in Go files.

ast-grep --lang go --pattern 'import $_ "nhooyr\.io/websocket"'

Length of output: 65

x/evm/tracers/firehose_test.go (1)

24-24: Verify import path for 'pbeth' package

The import statement at line 24 imports pbeth from github.com/evmos/ethermint/pb/sf/ethereum/type/v2. Since this repository is InjectiveLabs/ethermint, please verify that the import path is correct and aligns with the project's module path to prevent potential issues with module resolution.

If the pbeth package exists within the InjectiveLabs/ethermint repository, consider updating the import path accordingly.

x/evm/keeper/state_transition.go (2)

230-230: Verify the impact of setting res.Logs to nil after post-processing failure

Clearing res.Logs when the transaction fails in post-processing hooks ensures that no logs are emitted for failed transactions. Please verify that this aligns with the expected behavior and that downstream components handle the absence of logs appropriately.

Run the following script to check for any dependencies on res.Logs being present even after failures:

✅ Verification successful

Impact Verified: Setting res.Logs to nil correctly aligns with expected behavior and is appropriately handled by downstream components.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Search for usages of res.Logs after ApplyTransaction

rg --type go 'res\.Logs' --context 5

Length of output: 3202


Line range hint 346-370: Review balance adjustments in debug tracing mode

When cfg.DebugTrace is true, the code adjusts the sender's balance and nonce to simulate transaction execution:

  • Subtracts msg.GasPrice * msg.GasLimit from the sender's balance.
  • Increments the sender's nonce by 1.
  • Refunds the leftover gas after execution.

Please verify that these adjustments correctly emulate the actual transaction processing and do not interfere with state when commit is false. Ensure that this logic is thread-safe and does not affect other concurrent operations.

Run the following script to check for potential side effects in debug tracing mode:

x/evm/keeper/state_transition_test.go (3)

5-5: Approved: Added tracing package import

The import of the github.com/ethereum/go-ethereum/core/tracing package is appropriate for enabling tracing capabilities in the tests.


619-619: Verify usage of the initialized tracer

At line 619, tracer is initialized using types.NewTracer("", msg, rules). Ensure that this tracer is properly integrated into the EVM execution within the test to capture the intended tracing information.


660-676: Test case addition: "message applied with firehose tracer"

The new test case introduced for "message applied with firehose tracer" sets up a scenario to test message application using a firehose tracer. Verify that this test adequately covers the desired tracing behavior. Consider adding assertions to check the tracer's output to ensure it is capturing events as expected.

x/evm/statedb/statedb.go (1)

443-465: ⚠️ Potential issue

Verify interface compliance after method signature changes

The signatures of AddBalance, SubBalance, and SetBalance have been modified to include additional parameters for tracing. Please verify that these changes do not break the implementation of the vm.StateDB interface.

Run the following script to check interface conformity:

Also applies to: 469-491, 496-507

app/app.go (2)

1152-1154: Utility function ptr is correctly implemented

The generic function ptr[T any](t T) *T is well-defined and will be useful for obtaining pointers to values without verbose syntax.


1117-1150: Verify the correctness of field mappings in TmBlockHeaderToEVM

Please ensure that the mappings from tmproto.Header to ethtypes.Header are accurate. In particular, verify that:

  • block.DataHash is correctly mapped to TxHash.
  • block.LastResultsHash is appropriately used for ReceiptHash.
  • block.ProposerAddress corresponds to Coinbase.

Incorrect mappings could lead to inconsistent block headers and unexpected behavior in the EVM.

Run the following script to verify the field usages and mappings:

This script uses rg to locate and display the mappings within the code, helping confirm that each Tendermint header field is appropriately assigned to the Ethereum header field.

✅ Verification successful

Field mappings in TmBlockHeaderToEVM are correctly implemented.

  • block.DataHash is properly mapped to TxHash.
  • block.LastResultsHash is correctly assigned to ReceiptHash.
  • block.ProposerAddress accurately corresponds to Coinbase.
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify field mappings from tmproto.Header to ethtypes.Header in TmBlockHeaderToEVM.

# Expected: Each field from tmproto.Header should be correctly assigned to the corresponding field in ethtypes.Header.

# Search for the TmBlockHeaderToEVM function implementation
rg 'func TmBlockHeaderToEVM' -A 50

# Verify mapping of block.DataHash to TxHash
echo "Checking mapping of block.DataHash to TxHash:"
rg 'txHash\s*:=\s*ethcommon\.BytesToHash\(\s*block\.DataHash\s*\)'
rg 'TxHash:\s*txHash'

# Verify mapping of block.LastResultsHash to ReceiptHash
echo "Checking mapping of block.LastResultsHash to ReceiptHash:"
rg 'resultHash\s*:=\s*ethcommon\.BytesToHash\(\s*block\.LastResultsHash\s*\)'
rg 'ReceiptHash:\s*resultHash'

# Verify mapping of block.ProposerAddress to Coinbase
echo "Checking mapping of block.ProposerAddress to Coinbase:"
rg 'miner\s*:=\s*ethcommon\.BytesToAddress\(\s*block\.ProposerAddress\s*\)'
rg 'Coinbase:\s*miner'

Length of output: 3057

x/evm/tracers/firehose.go (4)

591-599: Issue: Transaction reset logic may not be consistent

In the OnTxEnd method, when f.transactionIsolated is true, the transaction is not reset immediately, but the comment mentions that resetting the transaction resets f.transactionTransient. This might lead to inconsistent state if OnTxReset is not called appropriately.

Please verify that OnTxReset is properly invoked after isolated transactions to reset the transaction state and that there's no risk of stale data remaining.


1144-1151: Issue: Skipping balance changes for self-destruct burn in backward compatibility

In the OnBalanceChange method, when applyBackwardCompatibility is true, balance changes with reason BalanceDecreaseSelfdestructBurn are ignored. This could lead to missing balance change events in the traced data.

Ensure that this behavior aligns with the expected backward compatibility requirements and that omitting these balance changes does not adversely affect downstream processes.


1405-1405: ⚠️ Potential issue

Issue: Unnecessary return type in panicInvalidState method

The method panicInvalidState is defined with a return type string but it always calls panic and does not return. Including a return type in this case is misleading and unnecessary.

Apply the following diff to remove the return type:

-func (f *Firehose) panicInvalidState(msg string, callerSkip int) string {
+func (f *Firehose) panicInvalidState(msg string, callerSkip int) {

Likely invalid or redundant comment.


17-17: ⚠️ Potential issue

Issue: Importing non-standard package slices

The import path "slices" is not part of the Go standard library prior to Go 1.21. If you are targeting an earlier Go version or if this is a custom package, ensure that the correct import path is used, such as "golang.org/x/exp/slices".

Apply the following diff to correct the import:

-	"slices"
+	"golang.org/x/exp/slices"

Likely invalid or redundant comment.

x/evm/handler_test.go Outdated Show resolved Hide resolved
x/evm/keeper/abci.go Outdated Show resolved Hide resolved
x/evm/types/tracer.go Show resolved Hide resolved
x/evm/types/tracer.go Outdated Show resolved Hide resolved
x/evm/keeper/keeper.go Outdated Show resolved Hide resolved
x/evm/statedb/statedb.go Outdated Show resolved Hide resolved
x/evm/tracers/firehose.go Show resolved Hide resolved
x/evm/tracers/firehose.go Show resolved Hide resolved
x/evm/tracers/firehose.go Show resolved Hide resolved
x/evm/tracers/firehose.go Show resolved Hide resolved
@Eduard-Voiculescu Eduard-Voiculescu marked this pull request as ready for review October 17, 2024 14:44
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 37

🧹 Outside diff range and nitpick comments (22)
x/evm/tracers/tracing.go (1)

7-12: Type alias declaration is good, but consider some improvements.

The BlockchainTracerFactory type alias is well-defined and documented. However, there are a few points to consider:

  1. The comment mentions receiving a parsed URL, but this isn't reflected in the function signature. Consider adding a URL parameter or clarifying how the URL is used.

  2. The comment suggests that the URL scheme determines which tracer to use, but this logic isn't implemented here. It might be helpful to add a TODO comment or clarify where this logic will be implemented.

  3. The backwardCompatibility parameter's purpose isn't explained in the comment. Consider adding a brief explanation of its role.

Would you like me to propose a revised version of the type alias and its documentation?

x/evm/tracing/context.go (3)

8-10: Consider a more concise name for the constant.

The type declaration CtxBlockchainTracerKeyType and its usage for the constant CtxBlockchainTracerKey provide good type safety. However, the constant name could be more concise while maintaining clarity.

Consider renaming the constant to TracerKey or BlockchainTracerKey to reduce redundancy:

-const CtxBlockchainTracerKey = CtxBlockchainTracerKeyType("evm_and_state_logger")
+const TracerKey = CtxBlockchainTracerKeyType("evm_and_state_logger")

12-14: LGTM: Function correctly sets the tracer in context. Consider a more concise name.

The SetCtxBlockchainTracer function correctly embeds the logger in the context using WithContext and WithValue. The implementation is sound.

Consider renaming the function to SetBlockchainTracer or SetTracer for brevity:

-func SetCtxBlockchainTracer(ctx sdk.Context, logger *Hooks) sdk.Context {
+func SetBlockchainTracer(ctx sdk.Context, logger *Hooks) sdk.Context {

16-28: LGTM: Function correctly retrieves the tracer from context. Suggest improvements to name and comment.

The GetCtxBlockchainTracer function correctly retrieves and type-checks the logger from the context. The implementation is sound and includes proper nil checks.

  1. Consider renaming the function to GetBlockchainTracer or GetTracer for brevity.
  2. Improve the comment to follow Go's documentation conventions:
-// GetCtxBlockchainTracer function to get the Cosmos specific [tracing.Hooks] struct
-// used to trace EVM blocks and transactions.
+// GetBlockchainTracer retrieves the Cosmos-specific tracing.Hooks struct
+// from the context. It returns nil if the tracer is not set or is of incorrect type.
-func GetCtxBlockchainTracer(ctx sdk.Context) *Hooks {
+func GetBlockchainTracer(ctx sdk.Context) *Hooks {
go.mod (1)

278-281: Approve replacement directives with a note on documentation and maintenance.

The use of custom forks for core components like cometbft and cosmos-sdk is approved. However, it's crucial to maintain these forks properly to avoid divergence from upstream.

Please consider the following actions:

  1. Document the reasons for using these forks in the project's README or a separate FORKS.md file.
  2. Create a maintenance plan to regularly sync these forks with their upstream repositories.
  3. Set up automated checks to notify when the forks are out of date with upstream.

Here's a script to help you check the status of your forks:

#!/bin/bash
# Description: Check the status of forks compared to upstream

# Test: Compare fork with upstream for each replaced dependency
for repo in cometbft cosmos-sdk go-ethereum; do
  echo "Checking $repo:"
  gh repo view InjectiveLabs/$repo --json 'createdAt,pushedAt,isInOrganization'
  echo "---"
done
x/evm/tracing/hooks.go (1)

12-15: Add documentation comments to exported function types.

To enhance code readability and adhere to Go conventions, consider adding documentation comments for the exported function types OnCosmosBlockStart, OnCosmosBlockEnd, and OnCosmosTxStart.

x/evm/tracers/firehose_test.go (2)

150-150: Typo in comment: 'codde' should be 'code'

In the comment at line 150, the word 'codde' is misspelled. It should be 'code' to maintain clarity in the documentation.

Apply this diff to fix the typo:

-	// On hard-fork, it happens that new fields are added, this test serves as a way to "detect" in codde
+	// On hard-fork, it happens that new fields are added, this test serves as a way to "detect" in code

353-356: Ensure consistent error messages and comments

In the block starting at line 353, the error message mentions re-running the test with a specific command. Consider formatting the command for better readability and ensuring that the path and test name are correctly referenced.

Apply this diff to improve the error message:

-				t.Fatalf("the golden file %q does not exist, re-run with 'GOLDEN_UPDATE=true go test ./... -run %q' to generate the intial version", goldenPath, t.Name())
+				t.Fatalf("The golden file %q does not exist. Re-run the test with the following command to generate the initial version:\nGOLDEN_UPDATE=true go test ./... -run %q", goldenPath, t.Name())
x/evm/keeper/state_transition_test.go (1)

653-653: Use suite.Require() for consistency in error assertions

At lines 653 and 717, the error assertions use require.NoError(suite.T(), err), whereas other parts of the test suite utilize suite.Require().NoError(err). For consistency and to leverage the testing suite's built-in assertion methods, consider using suite.Require() instead of directly calling require.

Apply this diff to align the assertions:

- require.NoError(suite.T(), err)
+ suite.Require().NoError(err)

Also applies to: 717-717

x/evm/statedb/statedb.go (5)

20-20: Import Statement Formatting

The import statement for cosmostracing should be grouped appropriately with other import statements, following Go's standard import grouping conventions.

Apply this diff to adjust the import grouping:

 import (
 	"fmt"
+	cosmostracing "github.com/evmos/ethermint/x/evm/tracing"
 	"math/big"
 	"sort"

63-63: Remove Redundant Empty Line

There is an extra empty line that is not necessary and can be removed to maintain code cleanliness.

Apply this diff to remove the redundant line:

 	// * Accounts

-

 type StateDB struct {

104-106: Add Comment for evmTracer Field

Consider adding a comment explaining the purpose of the evmTracer field in the StateDB struct for better code documentation.

Apply this diff to add the comment:

 	// events emitted by native action
 	nativeEvents sdk.Events

+	// EVM Tracer hooks for tracing EVM operations
 	evmTracer *cosmostracing.Hooks

Line range hint 126-131: Simplify Cache MultiStore Initialization

The conditional check for cacheMS initialization can be simplified for better readability.

Apply this diff to simplify the initialization:

 	} else {
 		// in unit test, it could be run with an uncached multistore
-		if cacheMS, ok = ctx.MultiStore().CacheWrap().(cachemulti.Store); !ok {
-			panic("expect the CacheWrap result to be cachemulti.Store")
-		}
+		cacheMS = ctx.MultiStore().CacheMultiStore().(cachemulti.Store)
 		commitMS = cacheMS.Write
 	}

396-397: Correct Function Comment Formatting

The comment for the ExecuteNativeAction function is not correctly formatted. Ensure that the comment immediately precedes the function definition without an empty line.

Apply this diff to adjust the comment formatting:

-// ExecuteNativeAction executes native action in isolate,
-// the writes will be reverted when either the native action itself fail
-// or the wrapping message call reverted.
+// ExecuteNativeAction executes a native action in isolation.
+// The writes will be reverted if the native action fails
+// or if the wrapping message call is reverted.
 func (s *StateDB) ExecuteNativeAction(contract common.Address, converter EventConverter, action func(ctx sdk.Context) error) error {
x/evm/keeper/grpc_query_test.go (2)

Line range hint 1109-1113: Adjust expPass to false for test case with invalid tracer

In the test case "invalid trace config - Invalid Tracer", the expPass is set to true. Since an invalid tracer is provided, the test should expect to fail. Update expPass to false to accurately reflect the expected outcome.

Apply this diff to fix the expPass value:

{
    msg: "invalid trace config - Invalid Tracer",
    malleate: func() {
        traceConfig = &types.TraceConfig{
            DisableStack:   true,
            DisableStorage: true,
            EnableMemory:   false,
            Tracer:         "invalid_tracer",
        }
    },
-   expPass:       true,
+   expPass:       false,
    traceResponse: "invalid_tracer is not defined",
},

Line range hint 1138-1143: Adjust expPass to false for test case with invalid chain ID

In the test case "invalid chain id", the expPass is set to true. Providing an invalid chain ID should cause the test to fail. Update expPass to false to accurately reflect the expected failure.

Apply this diff to fix the expPass value:

{
    msg: "invalid chain id",
    malleate: func() {
        traceConfig = nil
        tmp := sdkmath.NewInt(1)
        chainID = &tmp
    },
-   expPass:       true,
+   expPass:       false,
    traceResponse: "invalid chain id for signer",
},
x/evm/tracers/firehose.go (3)

975-980: Review backward compatibility handling for known issues

The code intentionally reproduces a known issue for backward compatibility:

if *f.applyBackwardCompatibility {
    if encodedData == "" {
        encodedData = "."
    }
}

While maintaining backward compatibility is important, embedding known bugs can be risky and may lead to technical debt. Consider documenting these sections clearly and planning for a future where old bugs can be phased out or handled differently.


1683-1684: Implement the FIXME: Create unit test for header changes

A FIXME comment indicates a need for a unit test:

// FIXME: Create a unit test that is going to fail as soon as any header is added in

Having this test will ensure that any changes to the block header structure are caught during development, preventing unintended side effects.

Would you like assistance in creating this unit test or opening a GitHub issue to track this task?


1723-1724: Reinstate Firehose tests to cover all transaction types

There's a FIXME comment suggesting the need to bring back certain tests:

// FIXME: Bring back Firehose test that ensures no new tx type are missed

Comprehensive testing of transaction types is crucial for maintaining compatibility with future protocol updates. Restoring or creating these tests can help prevent bugs related to unhandled transaction types.

Do you need help in restoring these tests or updating them to cover new transaction types?

x/evm/keeper/keeper_firehose.go (3)

14-24: Add GoDoc comment for exported function BlocksBloom

Consider adding a GoDoc comment to the exported function BlocksBloom to enhance code documentation and help other developers understand its purpose and usage.


26-53: Add GoDoc comment for exported function ToCosmosStartBlockEvent

Adding a GoDoc comment to the exported function ToCosmosStartBlockEvent would improve code readability and assist others in understanding its purpose and usage.


54-58: Add GoDoc comment for exported function ToCosmosEndBlockEvent

Consider adding a GoDoc comment to the exported function ToCosmosEndBlockEvent to improve code documentation and aid in understanding its functionality.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 5376e54 and 4e2ce71.

⛔ Files ignored due to path filters (1)
  • go.sum is excluded by !**/*.sum
📒 Files selected for processing (20)
  • app/app.go (0 hunks)
  • go.mod (6 hunks)
  • rpc/backend/tx_info.go (1 hunks)
  • x/evm/keeper/abci.go (2 hunks)
  • x/evm/keeper/config.go (4 hunks)
  • x/evm/keeper/grpc_query.go (2 hunks)
  • x/evm/keeper/grpc_query_test.go (12 hunks)
  • x/evm/keeper/keeper.go (5 hunks)
  • x/evm/keeper/keeper_firehose.go (1 hunks)
  • x/evm/keeper/state_transition.go (13 hunks)
  • x/evm/keeper/state_transition_test.go (6 hunks)
  • x/evm/statedb/statedb.go (9 hunks)
  • x/evm/statedb/statedb_test.go (6 hunks)
  • x/evm/tracers/firehose.go (1 hunks)
  • x/evm/tracers/firehose_test.go (1 hunks)
  • x/evm/tracers/registry.go (1 hunks)
  • x/evm/tracers/tracing.go (1 hunks)
  • x/evm/tracing/context.go (1 hunks)
  • x/evm/tracing/hooks.go (1 hunks)
  • x/evm/types/tracer.go (4 hunks)
💤 Files with no reviewable changes (1)
  • app/app.go
✅ Files skipped from review due to trivial changes (1)
  • rpc/backend/tx_info.go
🧰 Additional context used
🔇 Additional comments (38)
x/evm/tracers/tracing.go (2)

1-1: LGTM: Package declaration is appropriate.

The package name tracers is concise, descriptive, and follows Go naming conventions. It accurately reflects the purpose of the package and aligns with its location in the directory structure.


3-5: LGTM: Import statement is correct and necessary.

The import of github.com/evmos/ethermint/x/evm/tracing is required for the BlockchainTracerFactory type alias. The import statement follows Go conventions.

x/evm/tracers/registry.go (3)

5-8: LGTM: Well-designed interface.

The LiveTracerRegistry interface is well-defined with clear and purposeful methods. It follows the single responsibility principle and provides a solid contract for implementations.


12-16: LGTM: Proper initialization of the registry.

The NewLiveTracerRegistry function correctly initializes a new liveTracerRegistry with an empty map. This approach is idiomatic in Go and provides a clean way to create new instances of the registry.


10-20: LGTM: Good struct design and interface compliance check.

The liveTracerRegistry struct is appropriately designed with a map for storing tracer factories. The type assertion var _ LiveTracerRegistry = (*liveTracerRegistry)(nil) is a great practice, ensuring that liveTracerRegistry implements the LiveTracerRegistry interface at compile-time.

x/evm/tracing/context.go (2)

1-6: LGTM: Package declaration and imports are appropriate.

The package name "tracing" accurately reflects its purpose, and the imports are relevant to the functionality being implemented.


1-36: Overall assessment: Well-implemented tracing functionality with room for minor improvements.

The x/evm/tracing/context.go file introduces well-structured and necessary functionality for tracing in the EVM context. The code follows Go conventions and achieves its purpose effectively. The suggested improvements mainly focus on naming consistency and conciseness, which would enhance the overall code quality and readability.

Key points:

  1. Consider more concise names for constants and functions.
  2. Improve function comments to follow Go documentation conventions.
  3. Simplify the GetEthTracingHooks function implementation.

These changes will make the code more maintainable and easier to understand for other developers working on the project.

go.mod (2)

53-56: Approve indirect dependency updates with a note on testing.

The updates to indirect dependencies are beneficial for security and bug fixes. However, it's important to ensure these updates don't introduce any regressions.

Please run the following script to execute the test suite and check for any regressions:

Also applies to: 69-69, 210-210, 253-253, 255-256, 262-262


10-10: Approve main dependency updates with a note on compatibility.

The updates to main dependencies (cosmossdk.io/core, cosmossdk.io/x/tx, github.com/cometbft/cometbft) are good for keeping the project up-to-date. However, it's crucial to ensure these updates don't introduce breaking changes.

Please run the following script to check for any breaking changes or deprecations:

Also applies to: 18-18, 22-22

x/evm/keeper/abci.go (2)

20-20: Importing 'cosmostracing' package for tracing functionality

The addition of the cosmostracing import enables the new tracing capabilities implemented in the code.


28-29: Proper error handling when retrieving EVM Block Configuration

The code correctly handles potential errors from k.EVMBlockConfig(ctx, k.ChainID()), ensuring that any issues are gracefully managed.

x/evm/types/tracer.go (3)

77-86: Well-implemented error handling in NewLiveTracer

The NewLiveTracer function correctly handles errors during tracer initialization, enhancing the robustness of the tracer setup.


88-95: Proper initialization and error handling in NewFirehoseCosmosLiveTracer

The NewFirehoseCosmosLiveTracer function properly initializes the Firehose Cosmos tracer with comprehensive error handling, ensuring reliable tracer operation.


42-42: Consistent addition of Firehose tracer constant

The Firehose constant is added consistently alongside existing tracer constants, maintaining code readability and organization.

x/evm/keeper/config.go (5)

19-19: Approved: Updated import for tracing implementation

The import statement for cosmostracing correctly reflects the shift to the new tracing mechanism.


56-56: Approved: Updated Tracer field in EVMConfig struct

The Tracer field in the EVMConfig struct has been updated to use *cosmostracing.Hooks, aligning with the new tracing implementation.


129-135: Approved: Initialization of EVMConfig without Tracer field

The EVMConfig function initializes the EVMConfig struct without setting the Tracer field. This is acceptable since the Tracer can be set separately when needed.


137-149: Approved: Addition of EVMConfigWithTracer function

The new EVMConfigWithTracer function properly extends EVMConfig by setting the Tracer field when k.evmTracer is available. This enhances flexibility in configuring EVM tracing.


174-176: Approved: Correct integration of tracing hooks in VMConfig

The conditional assignment ensures that vmCfg.Tracer is set to cfg.Tracer.Hooks only when appropriate, integrating the new tracing hooks correctly into the VM configuration.

x/evm/keeper/keeper.go (4)

19-19: LGTM!

The import of cosmostracing is correctly added and aligns with the new tracing implementation.


36-36: Avoid duplicate imports with conflicting aliases

The package github.com/evmos/ethermint/x/evm/types is still imported twice: once unaliased and once as evmtypes. This can lead to confusion and potential conflicts in the code. Please consider importing the package once and using a consistent alias throughout the file.


207-208: Ensure thread safety when setting the tracer

The SetTracer method allows changing the evmTracer at runtime. If the Keeper is accessed concurrently, modifying evmTracer could lead to race conditions. Consider adding synchronization mechanisms (e.g., mutexes) or document that SetTracer should only be called during initialization.


142-146: Verify that InitChainer is invoked during module initialization

The new InitChainer method initializes the tracer during the module's startup. To ensure that the tracing hooks are set up correctly, verify that InitChainer is called appropriately in the module's lifecycle.

You can run the following script to check where InitChainer is called:

x/evm/tracers/firehose_test.go (1)

343-344: Undefined function 'ptr' in newFirehose initialization

The function ptr used at line 343 is undefined. This will cause a compilation error. Consider defining the ptr function or using an alternative method to obtain a pointer to a boolean value.

This issue was previously noted and remains unresolved.

x/evm/keeper/state_transition.go (1)

424-429: ⚠️ Potential issue

Verify nonce handling and Tracer notification

The stateDB.SetNonce call is commented out, and cfg.Tracer.OnNonceChange is invoked instead. Ensure that the sender's nonce is correctly updated in the state database and that the tracer accurately reflects nonce changes.

Confirm that omitting stateDB.SetNonce does not lead to inconsistent nonce values. If the nonce is managed elsewhere, ensure that this is documented. Additionally, verify that the tracer's OnNonceChange method correctly tracks the nonce update.

x/evm/keeper/grpc_query.go (2)

23-23: LGTM

The import statement for cosmostracing is appropriate and necessary for the updated tracing functionality.


723-725: LGTM

The assignment of cfg.Tracer to cosmostracing.Hooks correctly wraps the existing tracer.Hooks, enhancing the tracing capabilities.

x/evm/statedb/statedb.go (3)

450-464: Fix Error Handling Logic in Transfer Method

The tracing logic should only execute when there is no error (s.err == nil). However, if an error occurs after transferring funds, it may result in inconsistent state or missing traces.

Please ensure that errors are appropriately handled and consider whether tracing should occur even when an error is present.


552-557: Add Nil Check for oldCode in SetCode

To prevent potential panics when computing the hash of nil, add a check to ensure oldCode is not nil before hashing.


565-568: Ensure Correct Old Value Retrieval in SetState

In the SetState method, retrieve the old value before calling SetState to accurately capture the state change during tracing.

x/evm/keeper/grpc_query_test.go (4)

1197-1198: Confirm necessity of error handling for SetBalance

The addition of error handling for SetBalance is a good practice if the function can return an error. Please confirm whether suite.App.EvmKeeper.SetBalance actually returns an error. If it does not, the error check may be unnecessary.

To verify if SetBalance returns an error, you can inspect the method signature using the following command:

#!/bin/bash
# Description: Check the signature of `SetBalance` to see if it returns an error.

# Expectation: Determine if error handling is required.

rg --type go 'func\s+\(.*\)\s+SetBalance\(.*\)\s+error' x/evm/keeper/keeper.go

1218-1218: Confirm error handling when setting balance in TestTraceBlock

In TestTraceBlock, you're adding error handling after setting the balance:

err := suite.App.EvmKeeper.SetBalance(suite.Ctx, suite.Address, big.NewInt(1000000000000000000), types.DefaultEVMDenom)
suite.Require().NoError(err)

Please verify whether SetBalance returns an error. If it does not, adding error handling may be unnecessary.

To check if SetBalance returns an error, inspect its signature:

#!/bin/bash
# Description: Check if `SetBalance` returns an error.

rg --type go 'func\s+\(.*\)\s+SetBalance\(.*\)\s+error' x/evm/keeper/keeper.go

1082-1082: Verify gas value in traceResponse within TestTraceBlock

In the TestTraceBlock test cases, the traceResponse has gas set to zero. Ensure that this aligns with the actual gas usage during block tracing. If the gas used is non-zero, consider updating the expected traceResponse accordingly.

You can check the actual gas usage during block tracing with the following script:

#!/bin/bash
# Description: Check the gas used in block traces.

# Expectation: Confirm whether `gas` should be zero.

rg --type go 'traceResponse:\s*".*\\\"gas\\\":0.*"' x/evm/keeper/grpc_query_test.go

865-865: Verify the correctness of setting gas to zero in traceResponse

In the test cases within TestTraceTx, the expected traceResponse JSON strings have the gas value set to "gas":0. Typically, the gas value should reflect the actual gas used during execution. Please verify if setting the gas to zero is intentional and whether it aligns with the actual behavior of the traced transactions.

To ensure the accuracy of the expected gas values, you can check the actual gas used during the execution by running the following script:

x/evm/statedb/statedb_test.go (2)

71-194: Well-structured and comprehensive test cases added

The new test cases TestTracer_Balance, TestTracer_Nonce, TestTracer_Code, and TestTracer_SetStorage effectively enhance the test suite. They provide thorough coverage for tracking state changes in balances, nonces, codes, and storage, ensuring the StateDB behaves as expected.

Also applies to: 305-351, 534-618, 1070-1112


25-26: ⚠️ Potential issue

Avoid duplicate imports and inconsistent aliasing of packages

The package "github.com/evmos/ethermint/x/evm/types" is imported twice, once without an alias and once as evmtypes. This can lead to confusion and inconsistencies in the code. It's best to import the package once with a clear alias and use it consistently throughout the file.

Apply this diff to remove the duplicate import and use a consistent alias:

-	"github.com/evmos/ethermint/x/evm/types"
 	evmtypes "github.com/evmos/ethermint/x/evm/types"

Update all instances of types. to evmtypes. throughout the file.

Likely invalid or redundant comment.

x/evm/tracers/firehose.go (1)

74-76: Duplicate Comment Check

This comment appears similar to a past review comment. Please ensure that we are not duplicating previous feedback.

x/evm/keeper/keeper_firehose.go (1)

37-40: Ensure finalizedHeaderNumber is correct and non-negative

Subtracting 1 from h.Height may result in negative values when h.Height is 0 or 1. Please verify that finalizedHeaderNumber accurately represents the intended block number and handles edge cases appropriately.

x/evm/tracers/registry.go Outdated Show resolved Hide resolved
x/evm/tracers/registry.go Outdated Show resolved Hide resolved
x/evm/tracing/context.go Outdated Show resolved Hide resolved
x/evm/tracing/hooks.go Show resolved Hide resolved
x/evm/tracing/hooks.go Show resolved Hide resolved
x/evm/statedb/statedb_test.go Show resolved Hide resolved
x/evm/tracers/firehose.go Show resolved Hide resolved
x/evm/tracers/firehose.go Show resolved Hide resolved
x/evm/keeper/keeper_firehose.go Show resolved Hide resolved
x/evm/keeper/keeper_firehose.go Outdated Show resolved Hide resolved
- move tracer calls to storage changes higher up
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🧹 Outside diff range and nitpick comments (5)
x/evm/keeper/keeper.go (2)

141-145: LGTM: New InitChainer method added

The InitChainer method is a good addition for initializing the blockchain tracer. It correctly checks for the presence of a tracer and invokes the initialization callback if available.

Consider adding a comment explaining the purpose of this method and when it's expected to be called in the blockchain lifecycle. This would improve the code's documentation and make it easier for other developers to understand its role.


Line range hint 79-120: Potential issue: evmTracer field not initialized in NewKeeper

The NewKeeper function has been updated to remove the tracer string parameter, which aligns with the new tracing mechanism. However, the function doesn't initialize the new evmTracer field of the Keeper struct.

To prevent potential nil pointer dereferences, consider initializing the evmTracer field in the NewKeeper function. You could either:

  1. Add a parameter to NewKeeper to accept the tracer:
func NewKeeper(
    // ... other parameters ...
    evmTracer *cosmostracing.Hooks,
) *Keeper {
    // ... other initializations ...
    return &Keeper{
        // ... other fields ...
        evmTracer: evmTracer,
    }
}
  1. Or, if the tracer is always set later using SetTracer, initialize it to nil explicitly:
return &Keeper{
    // ... other fields ...
    evmTracer: nil,
}

This will make the initialization of the evmTracer field more explicit and reduce the risk of unexpected behavior.

x/evm/statedb/statedb.go (1)

396-397: Correct grammatical errors in the comment for clarity.

The comment has grammatical issues. Consider revising it to:

-// the writes will be reverted when either the native action itself fail
-// or the wrapping message call reverted.
+// The writes will be reverted when either the native action itself fails
+// or the wrapping message call is reverted.
x/evm/tracers/firehose.go (2)

225-225: Simplify redundant type conversion

The expression len([]byte(cfg)) is redundant because cfg is already a byte slice ([]byte). You can simplify it to len(cfg).

Apply this diff to simplify the code:

-	if len([]byte(cfg)) > 0 {
+	if len(cfg) > 0 {

1847-1850: Avoid unnecessary return statements

The explicit return at the end of newBlobHashesFromChain is unnecessary since the named return value out will be returned by default.

Apply this diff to simplify the code:

-	return
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 4e2ce71 and bc9cb03.

📒 Files selected for processing (5)
  • x/evm/handler_test.go (1 hunks)
  • x/evm/keeper/keeper.go (4 hunks)
  • x/evm/statedb/statedb.go (9 hunks)
  • x/evm/tracers/firehose.go (1 hunks)
  • x/evm/tracers/firehose_test.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • x/evm/tracers/firehose_test.go
🧰 Additional context used
🔇 Additional comments (14)
x/evm/keeper/keeper.go (3)

19-19: LGTM: New import added correctly

The new import for cosmostracing is added correctly and follows the standard Go import format. The alias is clear and descriptive.


68-69: LGTM: New evmTracer field added, consider thread safety

The new evmTracer field is correctly added to the Keeper struct. It's of type *cosmostracing.Hooks, which aligns with the new import.

As mentioned in a previous review, ensure thread safety when accessing evmTracer, especially if the Keeper instance might be accessed concurrently. Consider documenting any synchronization requirements or ensuring that evmTracer is only set during initialization.


206-208: LGTM: New SetTracer method added, consider thread safety and documentation

The SetTracer method is correctly implemented to set the evmTracer field of the Keeper.

As mentioned in a previous review, ensure thread safety when setting the tracer, especially if the Keeper instance might be accessed concurrently.

Consider the following improvements:

  1. Add more detailed documentation explaining when and how this method should be used.
  2. Implement a check to prevent setting the tracer more than once, similar to the SetHooks method in this file.

Example implementation:

// SetTracer sets the EVM tracer for the keeper.
// It should be called only once during initialization.
// It panics if called more than once.
func (k *Keeper) SetTracer(tracer *cosmostracing.Hooks) {
    if k.evmTracer != nil {
        panic("cannot set evm tracer twice")
    }
    k.evmTracer = tracer
}
x/evm/statedb/statedb.go (11)

20-20: Added import for EVM tracing functionality.

The import statement for cosmostracing enables EVM tracing capabilities within the module.


104-106: Introduced evmTracer field in StateDB struct.

Adding the evmTracer field allows the StateDB to utilize EVM tracing hooks for enhanced observability.


217-218: Updated GetBalance to retrieve balance using keeper.

The method now fetches the balance directly from the keeper, ensuring consistency and accurate balance retrieval.


449-464: Implemented balance change tracing in Transfer method.

The tracing logic correctly captures balance changes for both sender and recipient when s.err is nil, enhancing transaction observability.


468-490: Added tracing of balance increases in AddBalance method.

The implementation correctly handles the tracing of balance additions when no errors have occurred.


494-516: Added tracing of balance decreases in SubBalance method.

The method now accurately traces balance deductions, improving debuggability.


521-532: Enhanced SetBalance with balance change tracing.

The tracer captures balance updates appropriately when there are no errors, providing better insight into state changes.


552-562: Implemented code change tracing in SetCode method with proper nil checks.

The code correctly handles cases where oldCode might be nil, preventing potential panics and ensuring accurate tracing.


568-571: Added storage change tracing in SetState method.

The tracer captures state changes accurately by retrieving the old value before updating the state.


580-588: Implemented storage change tracing in SetStorage method.

The method correctly logs storage changes for each key-value pair, enhancing debugging and state monitoring.


539-544: 🛠️ Refactor suggestion

Remove redundant nil check for stateObject in SetNonce.

The stateObject returned by s.getOrNewStateObject(addr) will never be nil, so the if stateObject != nil check is unnecessary.

You can simplify the code by removing the redundant check:

 func (s *StateDB) SetNonce(addr common.Address, nonce uint64) {
 	stateObject := s.getOrNewStateObject(addr)
-	if stateObject != nil {
 		oldNonce := s.GetNonce(addr)
 		stateObject.SetNonce(nonce)

 		if s.evmTracer != nil && s.evmTracer.OnNonceChange != nil {
 			s.evmTracer.OnNonceChange(addr, oldNonce, nonce)
 		}
-	}
 }

Likely invalid or redundant comment.

x/evm/handler_test.go Outdated Show resolved Hide resolved
x/evm/tracers/firehose.go Show resolved Hide resolved
x/evm/tracers/firehose.go Outdated Show resolved Hide resolved
x/evm/tracers/firehose.go Show resolved Hide resolved
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 9

🧹 Outside diff range and nitpick comments (7)
x/evm/keeper/config.go (1)

156-165: LGTM: Updated VMConfig method to integrate new tracing mechanism.

The changes to the VMConfig method correctly integrate the new tracing mechanism. The conditional assignment of vmCfg.Tracer ensures compatibility with the new structure.

Consider simplifying the condition:

-if vmCfg.Tracer == nil && cfg.Tracer != nil && cfg.Tracer.Hooks != nil {
+if cfg.Tracer != nil && cfg.Tracer.Hooks != nil {
 	vmCfg.Tracer = cfg.Tracer.Hooks
}

This simplification is possible because vmCfg.Tracer is always nil when the condition is checked, as it's not set in the vm.Config struct initialization.

x/evm/keeper/state_transition_test.go (3)

645-707: LGTM: Comprehensive test for transaction application with tracing

The new TestApplyTransactionWithTracer function is a well-structured and valuable addition to the test suite. It effectively tests the integration of tracing with transaction application, using mock objects and custom hooks to verify the correct behavior.

Consider adding assertions to verify the content of the traced data, not just that the hooks were called. This could provide more confidence in the correctness of the tracing implementation.


709-791: LGTM: Comprehensive test for message application with configured tracer

The TestApplyMessageWithConfigTracer function is a valuable addition that extends the tracing test coverage. It effectively tests the ApplyMessageWithConfig function with a configured tracer, verifying various tracing hooks.

Consider parameterizing the test to cover different message types or configurations. This could increase the test coverage and ensure the tracing works correctly under various scenarios.


874-889: LGTM: Proper handling of tracer lifecycle in test cases

The additions to handle tracing in the TestApplyMessageWithConfig function are appropriate. They ensure that the tracer's OnBlockStart and OnBlockEnd methods are called when a tracer is configured, maintaining the correct state throughout the test.

Consider extracting the block creation logic into a helper function to improve readability and reusability. For example:

func createMockBlock(height int64, time int64) *ethtypes.Block {
    return ethtypes.NewBlockWithHeader(&ethtypes.Header{
        Number:     big.NewInt(height),
        Time:       uint64(time),
        Difficulty: big.NewInt(0),
    })
}

Then use it in the test:

config.Tracer.OnBlockStart(tracing.BlockEvent{
    Block: createMockBlock(suite.Ctx.BlockHeight(), suite.Ctx.BlockHeader().Time.Unix()),
    TD:    big.NewInt(0),
})
x/evm/keeper/state_transition.go (1)

251-258: Handle empty VmError when creating an error

In the deferred function, errors.New(res.VmError) is called. If res.VmError is an empty string, this will create an error with an empty message, which may not be meaningful. Consider checking if res.VmError is non-empty before creating the error to avoid potential confusion.

Apply this diff to handle empty VmError:

	defer func() {
		if cfg.Tracer != nil && cfg.Tracer.OnTxEnd != nil {
-			cfg.Tracer.OnTxEnd(
-				receipt,
-				errors.New(res.VmError),
-			)
+			var err error
+			if res.VmError != "" {
+				err = errors.New(res.VmError)
+			}
+			cfg.Tracer.OnTxEnd(
+				receipt,
+				err,
+			)
		}
	}()
x/evm/keeper/grpc_query.go (1)

Line range hint 649-658: Ensure safe conversion of traceConfig.Limit to int

When converting traceConfig.Limit to int, there is a potential risk of integer overflow on 32-bit systems if the limit exceeds the maximum value of int. Consider using a fixed-size integer type like int64 or adding a check to ensure the limit value is within the acceptable range.

Apply this diff to ensure safe conversion:

 logConfig := logger.Config{
     // ...
-    Limit:            int(traceConfig.Limit),
+    Limit:            int64(traceConfig.Limit),
 }
x/evm/statedb/statedb.go (1)

540-545: Consider handling nil stateObject explicitly in SetNonce

In the SetNonce method, if stateObject is nil, the method exits silently. To improve error handling, consider logging a warning or returning an error when stateObject is nil. This can help identify issues where the account does not exist.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 5d807a1 and f865e00.

📒 Files selected for processing (6)
  • x/evm/keeper/config.go (4 hunks)
  • x/evm/keeper/grpc_query.go (4 hunks)
  • x/evm/keeper/state_transition.go (14 hunks)
  • x/evm/keeper/state_transition_test.go (6 hunks)
  • x/evm/statedb/statedb.go (9 hunks)
  • x/evm/statedb/statedb_test.go (7 hunks)
🧰 Additional context used
🔇 Additional comments (17)
x/evm/keeper/config.go (4)

21-22: LGTM: Import change for new tracing implementation.

The addition of the cosmostracing import aligns with the transition to a new tracing mechanism, which is consistent with changes in other files.


57-57: LGTM: Updated EVMConfig struct with new tracing type.

The change of the Tracer field type to *cosmostracing.Hooks is consistent with the new tracing implementation and aligns with changes in other files.


130-136: LGTM: Updated EVMConfig method to use new tracing mechanism.

The changes to the EVMConfig method correctly integrate the new tracing mechanism by assigning k.evmTracer to the Tracer field of the cfg variable. This is consistent with the overall transition to the new tracing implementation.


Line range hint 1-165: Overall changes look good: Successful integration of new tracing mechanism.

The modifications in this file successfully integrate the new tracing mechanism based on cosmostracing. The changes are consistent across different methods and structs, aligning with the broader refactoring effort mentioned in the AI summary.

Key points:

  1. Import statements updated to include the new tracing package.
  2. EVMConfig struct updated to use the new tracing type.
  3. EVMConfig and VMConfig methods modified to properly integrate the new tracing mechanism.

These changes enhance the tracing capabilities of the EVM module while maintaining consistency with other related files.

x/evm/keeper/state_transition_test.go (2)

9-11: LGTM: New imports for tracing functionality

The added imports for Comet and tracing packages are appropriate for the new tracing functionality being introduced in the tests.


Line range hint 1-965: Summary: Tracing functionality well integrated into EVM keeper tests

The changes to state_transition_test.go successfully integrate tracing functionality into the EVM keeper tests. New test functions for applying transactions and messages with tracers have been added, and existing tests have been updated to support tracing. The additions provide good coverage of the new tracing features.

Key points:

  1. New imports for tracing packages have been correctly added.
  2. New test functions TestApplyTransactionWithTracer and TestApplyMessageWithConfigTracer comprehensively test tracing integration.
  3. Existing tests have been updated to support tracing where appropriate.
  4. A new MockCometInfo struct has been added for testing purposes.

Some minor improvements have been suggested:

  1. Initializing msg before passing it to NewTracer in TestApplyMessage.
  2. Adding assertions for traced data content in the new test functions.
  3. Parameterizing tests to cover more scenarios.
  4. Enhancing the MockCometInfo implementation for more meaningful tests.

Overall, these changes significantly improve the test coverage for the EVM keeper's tracing capabilities.

x/evm/statedb/statedb_test.go (3)

304-350: LGTM: Comprehensive test cases for nonce tracing

The TestTracer_Nonce function provides a good set of test cases covering various nonce change scenarios. The use of evmtypes.NewFirehoseCosmosLiveTracer() is consistent with the tracing functionality implementation.


70-193: ⚠️ Potential issue

Use consistent package alias for evmtypes across the code

The function NewFirehoseCosmosLiveTracer is called using different package aliases (types and evmtypes) in various places. This inconsistency can be confusing and may lead to errors.

Standardize the package alias usage by applying this diff:

-	t, err := types.NewFirehoseCosmosLiveTracer()
+	t, err := evmtypes.NewFirehoseCosmosLiveTracer()

Ensure that evmtypes is used consistently throughout the file.

Likely invalid or redundant comment.


57-64: 🛠️ Refactor suggestion

Avoid unnecessary string conversions in balanceChangesValues

The function balanceChangesValues converts numerical values to strings for formatting. If you switch old and new to use *big.Int, you can format them directly without intermediate string conversion.

Modify the formatting to accommodate *big.Int:

 func balanceChangesValues(changes []balanceChange) string {
 	out := make([]string, len(changes))
 	for i, change := range changes {
-		out[i] = fmt.Sprintf("{%q, %q, ethtracing.BalanceChangeReason(%d)}", change.old, change.new, change.reason)
+		out[i] = fmt.Sprintf("{%v, %v, ethtracing.BalanceChangeReason(%d)}", change.old, change.new, change.reason)
 	}

 	return strings.Join(out, "\n")
 }

Likely invalid or redundant comment.

x/evm/keeper/grpc_query.go (4)

26-27: Import of cosmostracing package added

The import statement for cosmostracing is necessary for the new tracing functionalities introduced.


666-666: Conditional override of the default tracer

The code correctly checks if a custom tracer is specified in traceConfig.Tracer and overrides the default tracer accordingly.


668-676: Proper initialization of the tracer context

The tracer context tCtx is properly initialized with transaction and block information, ensuring accurate tracing.


724-726: Assignment of tracer hooks to the EVM configuration

The tracer hooks are correctly assigned to cfg.Tracer using cosmostracing.Hooks, integrating the new tracing mechanism into the EVM configuration.

x/evm/statedb/statedb.go (4)

174-176: Good use of nil checks before tracing in AddLog

The added nil checks for log, s.evmTracer, and s.evmTracer.OnLog ensure that there will be no nil pointer dereference when calling s.evmTracer.OnLog(log). This enhances the robustness of the code.


569-572: Correct order of operations in SetState for accurate tracing

You correctly perform the tracing of storage changes before modifying the state in SetState. This ensures that the old value is captured accurately in the trace.


581-586: Properly tracing all storage changes in SetStorage

In SetStorage, you iterate over each key-value pair and trace the changes before updating the state. This ensures comprehensive tracking of all storage modifications.


553-563: Safely handling nil oldCode in SetCode

By checking if oldCode is nil before computing its hash in SetCode, you prevent potential panics due to nil pointer dereferences. This enhances the stability of the code.

x/evm/keeper/state_transition_test.go Outdated Show resolved Hide resolved
x/evm/statedb/statedb_test.go Show resolved Hide resolved
x/evm/statedb/statedb_test.go Show resolved Hide resolved
x/evm/statedb/statedb_test.go Show resolved Hide resolved
x/evm/statedb/statedb_test.go Show resolved Hide resolved
x/evm/keeper/state_transition.go Show resolved Hide resolved
Comment on lines +421 to +422
// Why do we want to set the nonce in the statedb twice here?

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Clarify the necessity of setting the nonce twice

The comment questions why the sender's nonce is set twice in the state database. This could indicate redundant code or an area needing clarification. Please investigate whether both nonce assignments are necessary. If they are, add explanatory comments to justify the repeated setting for future maintainability.

Would you like assistance in reviewing the nonce management to ensure it's correct and necessary?

x/evm/keeper/state_transition.go Outdated Show resolved Hide resolved
@arrivets arrivets self-requested a review October 22, 2024 13:49
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

🧹 Outside diff range and nitpick comments (6)
x/evm/tracing/context.go (2)

9-11: LGTM: Custom type and constant are well-defined.

The BlockchainTracerKeyType and BlockchainTracerKey are appropriately defined and provide type safety for context keys. The naming is clear and follows Go conventions.

Consider adding a brief comment explaining the purpose of BlockchainTracerKey, especially regarding its dual use for EVM and state logging:

// BlockchainTracerKey is the context key for storing EVM and state logging hooks
const BlockchainTracerKey = BlockchainTracerKeyType("evm_and_state_logger")

17-27: LGTM: GetTracingHooks function is well-implemented with proper error handling.

The GetTracingHooks function correctly retrieves the hooks from the context, handling potential nil values and type mismatches appropriately.

Consider optimizing the function by combining the nil check and type assertion:

func GetTracingHooks(ctx sdk.Context) *Hooks {
	if hooks, ok := ctx.Context().Value(BlockchainTracerKey).(*Hooks); ok {
		return hooks
	}
	return nil
}

This change reduces the number of checks and makes the function more concise while maintaining the same functionality.

x/evm/types/tracer.go (1)

Line range hint 1-83: Summary of changes in x/evm/types/tracer.go

The changes in this file enhance the tracing capabilities by adding support for the Firehose tracer. The new NewFirehoseCosmosLiveTracer function is well-implemented with proper error handling. However, the NewTracer function could benefit from improved error handling, particularly in the Firehose and default cases.

Overall, these changes align well with the PR objectives of enhancing tracing capabilities. To further improve the code:

  1. Address the error handling issue in the NewTracer function as suggested.
  2. Consider adding unit tests for the new NewFirehoseCosmosLiveTracer function and the updated NewTracer function to ensure they behave as expected under various conditions.
x/evm/keeper/state_transition_test.go (2)

645-707: LGTM: Comprehensive test for transaction application with tracer

The TestApplyTransactionWithTracer function is well-structured and covers important aspects of tracing during transaction application. It sets up the necessary mocks, overrides tracer hooks, and verifies that the hooks are called and the transaction is applied correctly.

Consider adding assertions for the following to make the test even more robust:

  1. Verify the contents of the tracer's collected data (if accessible).
  2. Assert on specific gas values in the OnGasChange hook.
  3. Check for any errors returned by the tracer hooks.

709-791: LGTM: Thorough test for message application with config tracer

The TestApplyMessageWithConfigTracer function is well-implemented and provides comprehensive coverage for applying a message with a configured tracer. It properly sets up the environment, overrides necessary hooks, and verifies their execution along with the message application result.

To further enhance the test:

  1. Consider adding assertions for the specific values passed to each hook (e.g., gas values, depth, addresses).
  2. You might want to test with different message types or configurations to ensure the tracer behaves correctly in various scenarios.
x/evm/tracing/hooks.go (1)

35-41: Add comments for exported types to enhance documentation.

The exported structs CosmosStartBlockEvent and CosmosEndBlockEvent lack accompanying comments. According to Go conventions, each exported type should have a comment starting with the type's name to provide clarity and improve generated documentation.

Apply this diff to add the missing comments:

+// CosmosStartBlockEvent represents the event data for the start of a Cosmos block.
 type CosmosStartBlockEvent struct {
 	CosmosHeader *types.Header
 	BaseFee      *big.Int
 	GasLimit     uint64
 	Coinbase     common.Address
 	Finalized    *ethtypes.Header
 }

+// CosmosEndBlockEvent represents the event data for the end of a Cosmos block.
 type CosmosEndBlockEvent struct {
 	LogsBloom []byte
 }

Also applies to: 43-45

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between f865e00 and 0803635.

📒 Files selected for processing (7)
  • x/evm/keeper/abci.go (2 hunks)
  • x/evm/keeper/keeper.go (4 hunks)
  • x/evm/keeper/state_transition_test.go (6 hunks)
  • x/evm/tracers/firehose.go (1 hunks)
  • x/evm/tracing/context.go (1 hunks)
  • x/evm/tracing/hooks.go (1 hunks)
  • x/evm/types/tracer.go (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • x/evm/keeper/abci.go
  • x/evm/keeper/keeper.go
🧰 Additional context used
🔇 Additional comments (8)
x/evm/tracing/context.go (3)

1-7: LGTM: Package declaration and imports are appropriate.

The package name "tracing" accurately reflects the functionality being implemented, and the imports are necessary and correctly specified.


13-15: LGTM: SetTracingHooks function is well-implemented.

The SetTracingHooks function correctly uses the SDK context and the custom BlockchainTracerKey to store the tracing hooks. The implementation is concise and maintains the SDK context type.


1-27: Overall, excellent implementation of tracing context management.

This new file introduces a clean and efficient way to manage tracing hooks within the Cosmos SDK context. The implementation aligns well with Go best practices and Cosmos SDK patterns. The custom key type, constant, and functions provide a robust mechanism for setting and retrieving tracing hooks in the EVM context.

A few minor suggestions have been made to further improve documentation and optimize the code, but these are not critical. Great job on implementing this tracing functionality!

x/evm/types/tracer.go (3)

19-32: LGTM: Import statements updated correctly

The new import statements are appropriate for the added functionality. They include necessary packages for error handling, tracing, and Cosmos-specific implementations.


40-40: LGTM: Firehose constant added

The Firehose constant is appropriately defined and follows the existing naming convention for tracer types.


75-82: LGTM: Well-implemented NewFirehoseCosmosLiveTracer function

The NewFirehoseCosmosLiveTracer function is well-structured and follows Go best practices:

  1. It properly initializes the Cosmos-specific Firehose tracer.
  2. Error handling is implemented correctly, with a descriptive error message that wraps the original error.
  3. The function signature clearly indicates the return types, including the potential for an error.

This is a good example of how to implement new functionality with proper error handling.

x/evm/keeper/state_transition_test.go (1)

9-11: LGTM: New imports for tracing and Comet integration

The added imports for comet, tracing, and cosmostracing are appropriate for the new test cases and functionality introduced in this file.

x/evm/tracing/hooks.go (1)

1-45: LGTM!

The code is well-structured and effectively extends the EVM tracing hooks with Cosmos-specific events.

x/evm/types/tracer.go Outdated Show resolved Hide resolved
x/evm/keeper/state_transition_test.go Show resolved Hide resolved
Comment on lines +457 to +463
if event.Block.Transactions().Len() > 0 {
panic(fmt.Sprintf("The tracer received an `OnSkippedBlock` block #%d (%s) with %d transactions, this according to core/blockchain.go should never happen and is an error",
event.Block.NumberU64(),
event.Block.Hash().Hex(),
event.Block.Transactions().Len(),
))
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Handle unexpected conditions without panicking

In the OnSkippedBlock method, the code panics when it encounters an OnSkippedBlock event with transactions:

if event.Block.Transactions().Len() > 0 {
    panic(fmt.Sprintf("The tracer received an `OnSkippedBlock` block #%d (%s) with %d transactions, this according to core/blockchain.go should never happen and is an error",
        event.Block.NumberU64(),
        event.Block.Hash().Hex(),
        event.Block.Transactions().Len(),
    ))
}

Using panic can cause the entire application to crash, which is undesirable in production environments. Instead, consider handling this unexpected condition more gracefully by logging an error and returning it to be handled upstream.

Apply this diff to handle the error without panicking:

 if event.Block.Transactions().Len() > 0 {
-    panic(fmt.Sprintf("The tracer received an `OnSkippedBlock` block #%d (%s) with %d transactions, this according to core/blockchain.go should never happen and is an error",
-        event.Block.NumberU64(),
-        event.Block.Hash().Hex(),
-        event.Block.Transactions().Len(),
-    ))
+    errMsg := fmt.Sprintf("Received OnSkippedBlock with transactions (block #%d, hash %s, tx count %d)",
+        event.Block.NumberU64(),
+        event.Block.Hash().Hex(),
+        event.Block.Transactions().Len())
+    log.Error(errMsg)
+    return errors.New(errMsg)
 }

x/evm/tracers/firehose.go Show resolved Hide resolved
Comment on lines +1621 to +1624
if err := os.WriteFile("/tmp/firehose_writer_failed_print.log", []byte(errstr), 0644); err != nil {
fmt.Println(errstr)
}

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Avoid hardcoding file paths and improve error handling

The code writes an error message to a hardcoded file path /tmp/firehose_writer_failed_print.log with fixed permissions:

errstr := fmt.Sprintf("\nFIREHOSE FAILED WRITING %dx: %s\n", loops, err)
if err := os.WriteFile("/tmp/firehose_writer_failed_print.log", []byte(errstr), 0644); err != nil {
    fmt.Println(errstr)
}

Hardcoding file paths can lead to security issues and makes the application less portable. Additionally, using fixed permissions may expose sensitive information. Consider using a configurable logging mechanism and avoid writing directly to hardcoded file paths.

Apply this diff to address the issue:

-errstr := fmt.Sprintf("\nFIREHOSE FAILED WRITING %dx: %s\n", loops, err)
-if err := os.WriteFile("/tmp/firehose_writer_failed_print.log", []byte(errstr), 0644); err != nil {
-    fmt.Println(errstr)
-}
+log.Error("Failed to write to firehose after multiple attempts", "attempts", loops, "error", err)

Copy link

@arrivets arrivets left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good overall.

It would be good to add something in app.go that reads the evm.tracer config flag and sets the tracer appropriately. For all the possible values of that flag

app/app.go Outdated Show resolved Hide resolved
x/evm/types/tracer.go Outdated Show resolved Hide resolved
x/evm/types/tracer.go Outdated Show resolved Hide resolved
x/evm/keeper/state_transition_test.go Outdated Show resolved Hide resolved
x/evm/statedb/statedb.go Show resolved Hide resolved
server/config/toml.go Show resolved Hide resolved
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 0803635 and bd3ef46.

📒 Files selected for processing (1)
  • x/evm/types/tracer.go (3 hunks)
🧰 Additional context used
🔇 Additional comments (3)
x/evm/types/tracer.go (3)

29-32: Import statements correctly register the Firehose tracer

The added import statements and comments effectively ensure that importing the tracers package triggers its init method, registering the Firehose tracer in the LiveDirectory. This is important for the tracers to function properly.


40-40: Definition of Firehose tracer constant

The addition of the Firehose constant aligns with the new tracer functionality being introduced.


64-64: ⚠️ Potential issue

Handle errors returned by tracers.LiveDirectory.New

In the default case, the error from tracers.LiveDirectory.New("noop", nil) is being ignored. Proper error handling enhances robustness by preventing potential issues if the initialization fails.

Apply this diff to handle the error:

 default:
     // Use noop tracer by default
-    hooks, _ = tracers.LiveDirectory.New("noop", nil)
+    hooks, err = tracers.LiveDirectory.New("noop", nil)
+    if err != nil {
+        return &tracers.Tracer{}, fmt.Errorf("failed to initialize noop tracer: %w", err)
+    }

Likely invalid or redundant comment.

x/evm/types/tracer.go Show resolved Hide resolved
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Outside diff range and nitpick comments (1)
app/app.go (1)

801-820: Consider using constants and improving error handling.

While the tracer initialization logic is functionally correct, consider these improvements:

  1. Define constants for tracer types to avoid magic strings
  2. Consider returning an error instead of panicking for unsupported tracers

Apply this diff to improve the code:

+const (
+    TracerFirehose   = "firehose"
+    TracerAccessList = "access_list"
+)

-	tracer := cast.ToString(appOpts.Get(srvflags.EVMTracer))
+	tracerType := cast.ToString(appOpts.Get(srvflags.EVMTracer))

-	if tracer == "firehose" {
+	if tracerType == TracerFirehose {
 		liveTracer, err := evmtypes.NewFirehoseCosmosLiveTracer()
 		if err != nil {
 			panic(err)
 		}
 		app.EvmKeeper.SetTracer(liveTracer)
 		app.evmTracer = liveTracer
-	} else if tracer == "access_list" {
-		panic("access_list tracer is not supported")
+	} else if tracerType == TracerAccessList {
+		return fmt.Errorf("access_list tracer is not supported")
-	} else if tracer != "" {
-		liveTracer := evmtypes.NewTracer(tracer, nil, ethparams.Rules{})
+	} else if tracerType != "" {
+		liveTracer := evmtypes.NewTracer(tracerType, nil, ethparams.Rules{})
 		t := &evmtracing.Hooks{
 			Hooks: liveTracer.Hooks,
 		}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between bd3ef46 and 7789c56.

📒 Files selected for processing (2)
  • app/app.go (6 hunks)
  • server/start.go (1 hunks)
🧰 Additional context used
🔇 Additional comments (4)
server/start.go (1)

222-222: Verify the firestore tracer implementation

The EVMTracer flag description has been updated to include "firestore" as a new tracer type. Let's verify that the corresponding implementation exists.

app/app.go (3)

139-139: LGTM: Clean import addition.

The new import for EVM tracing is properly placed and aliased.


253-254: LGTM: Clean struct field addition.

The evmTracer field is properly defined as a pointer to avoid unnecessary copying and follows Go naming conventions.


895-897: LGTM: Consistent tracer integration.

The tracer integration is consistently implemented across BeginBlocker, EndBlocker, and InitChainer methods.

Also applies to: 916-918

app/app.go Outdated Show resolved Hide resolved
app/app.go Outdated Show resolved Hide resolved
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 7789c56 and 7db3bd1.

📒 Files selected for processing (1)
  • app/app.go (7 hunks)
🧰 Additional context used
🔇 Additional comments (3)
app/app.go (3)

254-254: Addition of evmTracer field is appropriate

The addition of the evmTracer field to the EthermintApp struct allows for proper management of EVM tracing hooks throughout the application.


869-875: Good job extracting EVM initialization into a helper method

Extracting the EVM initialization logic into the initializeEVM method reduces code duplication and enhances maintainability.


801-821: Tracer setup logic appears correct

The code correctly initializes the EVM tracer based on the application options, allowing for different tracer types to be used as needed.

Comment on lines +886 to +891
if app.evmTracer != nil {
ctx = evmtracing.SetTracingHooks(ctx, app.evmTracer)
}

app.initializeEVM(ctx)

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Consider extracting tracing hook setup into a helper method

The code to set up tracing hooks is duplicated in BeginBlocker, EndBlocker, and InitChainer. Extracting this into a helper method can improve code readability and maintainability.

Apply this diff to extract the tracing hook setup:

+func (app *EthermintApp) setTracingHooks(ctx sdk.Context) sdk.Context {
+  if app.evmTracer != nil {
+    ctx = evmtracing.SetTracingHooks(ctx, app.evmTracer)
+  }
+  return ctx
+}

Then update BeginBlocker:

 func (app *EthermintApp) BeginBlocker(ctx sdk.Context) (sdk.BeginBlock, error) {
-  if app.evmTracer != nil {
-    ctx = evmtracing.SetTracingHooks(ctx, app.evmTracer)
-  }
+  ctx = app.setTracingHooks(ctx)

   app.initializeEVM(ctx)
   return app.ModuleManager.BeginBlock(ctx)
 }

Similarly update EndBlocker and InitChainer:

 func (app *EthermintApp) EndBlocker(ctx sdk.Context) (sdk.EndBlock, error) {
-  if app.evmTracer != nil {
-    ctx = evmtracing.SetTracingHooks(ctx, app.evmTracer)
-  }
+  ctx = app.setTracingHooks(ctx)

   return app.ModuleManager.EndBlock(ctx)
 }
 func (app *EthermintApp) InitChainer(ctx sdk.Context, req *abci.RequestInitChain) (*abci.ResponseInitChain, error) {
-  if app.evmTracer != nil {
-    ctx = evmtracing.SetTracingHooks(ctx, app.evmTracer)
-  }
+  ctx = app.setTracingHooks(ctx)

   app.initializeEVM(ctx)
   return app.ModuleManager.InitGenesis(ctx, app.appCodec, genesisState)
 }

Also applies to: 897-900, 918-923

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Outside diff range and nitpick comments (2)
x/evm/keeper/state_transition_test.go (2)

646-708: LGTM: Transaction tracer test implementation

The test properly verifies the basic tracer hooks for transaction lifecycle.

Consider adding assertions for the hook parameters to ensure they contain the expected values:

 t.OnCosmosTxStart = func(vm *tracing.VMContext, tx *ethtypes.Transaction, hash common.Hash, from common.Address) {
     startTxHook(vm, tx, hash, from)
     onCosmosTxStartHookCalled = true
+    suite.Assert().Equal(suite.Address, from)
+    suite.Assert().NotNil(vm)
 }

710-792: LGTM: Config tracer test implementation

The test comprehensively verifies all tracer hooks for detailed transaction tracing.

Consider adding assertions for gas changes to verify the expected gas consumption:

 t.OnGasChange = func(old, new uint64, reason tracing.GasChangeReason) {
     gasChangedHook(old, new, reason)
     onGasChangedHookCalled = true
+    suite.Assert().Greater(old, new, "Gas should decrease during execution")
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 7db3bd1 and ffcfd44.

📒 Files selected for processing (3)
  • x/evm/keeper/state_transition.go (12 hunks)
  • x/evm/keeper/state_transition_test.go (5 hunks)
  • x/evm/types/errors.go (2 hunks)
🧰 Additional context used
🔇 Additional comments (5)
x/evm/types/errors.go (1)

120-121: LGTM! Error registration follows best practices.

The error registration is well-implemented:

  • Uses the standard errorsmod.Register pattern
  • Provides a clear and descriptive error message
  • Maintains consistent formatting with other error definitions

Note: Update the error code constant reference after fixing the typo.

x/evm/keeper/state_transition.go (1)

371-388: LGTM: Well-structured tracer initialization and callback handling

The implementation correctly:

  • Sets the tracer in the stateDB
  • Handles both OnCosmosTxStart and OnTxStart callbacks
  • Documents the precedence of OnCosmosTxStart over OnTxStart
x/evm/keeper/state_transition_test.go (3)

9-11: LGTM: Import additions and tracer integration

The new imports and tracer integration in the ApplyMessage test are appropriate for the added tracing functionality.

Also applies to: 637-638


874-890: LGTM: Block tracer hooks integration

The block start/end hooks are properly integrated into the existing test.


945-966: 🛠️ Refactor suggestion

Enhance MockCometInfo implementation

The current implementation returns zero values which may not provide adequate test coverage. This concern was raised in previous reviews and remains valid.

Consider implementing a more realistic mock as previously suggested:

 type MockCometInfo struct {
+    evidence       comet.EvidenceList
+    validatorsHash []byte
+    proposerAddr   []byte
+    lastCommit     comet.CommitInfo
 }

 func NewMockCometInfo() *MockCometInfo {
-    return &MockCometInfo{}
+    return &MockCometInfo{
+        validatorsHash: []byte("mock_validators_hash"),
+        proposerAddr:   []byte("mock_proposer_address"),
+    }
 }

 func (c *MockCometInfo) GetEvidence() comet.EvidenceList {
-    return nil
+    return c.evidence
 }

 func (c *MockCometInfo) GetValidatorsHash() []byte {
-    return []byte{}
+    return c.validatorsHash
 }

 func (c *MockCometInfo) GetProposerAddress() []byte {
-    return []byte{}
+    return c.proposerAddr
 }

 func (c *MockCometInfo) GetLastCommit() comet.CommitInfo {
-    return nil
+    return c.lastCommit
 }

x/evm/types/errors.go Show resolved Hide resolved
x/evm/keeper/state_transition.go Show resolved Hide resolved
@arrivets arrivets merged commit dd4800f into develop Oct 23, 2024
8 of 9 checks passed
@InjectiveLabs InjectiveLabs deleted a comment from coderabbitai bot Oct 28, 2024
@InjectiveLabs InjectiveLabs deleted a comment from socket-security bot Oct 28, 2024
@InjectiveLabs InjectiveLabs deleted a comment from socket-security bot Oct 28, 2024
@kakysha kakysha deleted the firehose branch October 29, 2024 14:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants