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

feat(evm): typed events for contract creation, contract execution and transfer #1971

Merged
merged 7 commits into from
Jul 24, 2024

Conversation

onikonychev
Copy link
Contributor

@onikonychev onikonychev commented Jul 23, 2024

Summary by CodeRabbit

  • New Features

    • Introduced typed events for contract creation, execution, and transfer, enhancing event tracking capabilities in the Ethereum Virtual Machine (EVM).
    • Added new message definitions for event handling, including EventTransfer, EventContractDeployed, and EventContractExecuted.
    • Enhanced transaction management with new functionality for executing smart contracts.
  • Bug Fixes

    • Improved error handling and event assertions in Ethereum transaction tests for better reliability.
  • Documentation

    • Updated CHANGELOG.md to reflect new features and enhancements.
  • Refactor

    • Renamed test functions for improved clarity and organization.

@onikonychev onikonychev requested a review from a team as a code owner July 23, 2024 11:54
Copy link
Contributor

coderabbitai bot commented Jul 23, 2024

Walkthrough

The recent updates to the NibiruChain project significantly enhance the Ethereum Virtual Machine (EVM) functionality by introducing typed events for contract interactions, improving event tracking and monitoring capabilities. Additionally, new structures and functions facilitate contract execution and testing, while existing tests have been refined for better clarity and robustness. Overall, these changes streamline event management and transaction handling, enhancing usability and performance.

Changes

Files Change Summary
CHANGELOG.md, proto/eth/evm/v1/events.proto Added typed events for contract creation, execution, and transfer to improve event clarity.
x/evm/evmtest/smart_contract.go, x/evm/evmtest/tx.go Introduced ArgsExecuteContract struct and enhanced transaction creation with new parameters.
x/evm/evmtest/smart_contract_test.go Added test for contract execution and updated existing tests for better validation and robustness.
x/evm/keeper/grpc_query_test.go, x/evm/keeper/msg_ethereum_tx_test.go Renamed a test function and added new tests for contract execution, streamlining test case handling.
x/evm/keeper/msg_server.go Enhanced ApplyEvmTx function to emit typed events based on transaction types for better tracking.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant EVM
    participant EventEmitter
    User->>EVM: Create/Execute Contract
    EVM->>EventEmitter: Emit EventContractDeployed (for creation)
    EVM->>EventEmitter: Emit EventContractExecuted (for execution)
    EVM->>EventEmitter: Emit EventTransfer (if transfer occurs)
Loading

🐇 "In the realm of code, we hop and play,
New events and features brighten the way!
With contracts created, executed with flair,
Our EVM dances, a sight so rare!
So let’s celebrate, with joy and cheer,
In the world of blockchain, there’s nothing to fear!" 🌟


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share
Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (invoked as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

codecov bot commented Jul 23, 2024

Codecov Report

Attention: Patch coverage is 73.46939% with 13 lines in your changes missing coverage. Please review.

Project coverage is 66.00%. Comparing base (afc7c0f) to head (123ae5d).

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1971      +/-   ##
==========================================
+ Coverage   65.95%   66.00%   +0.05%     
==========================================
  Files         258      258              
  Lines       16384    16432      +48     
==========================================
+ Hits        10806    10846      +40     
  Misses       4772     4772              
- Partials      806      814       +8     
Files Coverage Δ
x/evm/keeper/msg_server.go 72.38% <100.00%> (+0.80%) ⬆️
x/evm/evmtest/smart_contract.go 83.67% <83.33%> (-0.95%) ⬇️
x/evm/evmtest/tx.go 0.00% <0.00%> (ø)

... and 2 files with indirect coverage changes

Base automatically changed from on/refactor-evm-events to main July 23, 2024 18:46
@onikonychev onikonychev enabled auto-merge (squash) July 23, 2024 19:11
Copy link
Contributor

@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: 3

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between afc7c0f and 9155dd0.

Files ignored due to path filters (1)
  • x/evm/events.pb.go is excluded by !**/*.pb.go
Files selected for processing (8)
  • CHANGELOG.md (1 hunks)
  • proto/eth/evm/v1/events.proto (1 hunks)
  • x/evm/evmtest/smart_contract.go (3 hunks)
  • x/evm/evmtest/smart_contract_test.go (2 hunks)
  • x/evm/evmtest/tx.go (2 hunks)
  • x/evm/keeper/grpc_query_test.go (1 hunks)
  • x/evm/keeper/msg_ethereum_tx_test.go (5 hunks)
  • x/evm/keeper/msg_server.go (1 hunks)
Files skipped from review due to trivial changes (1)
  • x/evm/keeper/grpc_query_test.go
Additional context used
GitHub Check: codecov/patch
x/evm/evmtest/smart_contract.go

[warning] 53-53: x/evm/evmtest/smart_contract.go#L53
Added line #L53 was not covered by tests


[warning] 106-106: x/evm/evmtest/smart_contract.go#L106
Added line #L106 was not covered by tests

x/evm/evmtest/tx.go

[warning] 77-79: x/evm/evmtest/tx.go#L77-L79
Added lines #L77 - L79 were not covered by tests


[warning] 86-88: x/evm/evmtest/tx.go#L86-L88
Added lines #L86 - L88 were not covered by tests


[warning] 94-96: x/evm/evmtest/tx.go#L94-L96
Added lines #L94 - L96 were not covered by tests

Additional comments not posted (11)
x/evm/evmtest/smart_contract_test.go (1)

52-68: Verify the function usage and add assertions.

The test function TestExecuteContractTxMsg is well-structured. Ensure that all function calls to ExecuteContractTxMsg match the new signature.

Additionally, consider adding assertions to validate the expected state after the transaction execution.

+	// Add assertions to validate the expected state after execution.
+	// Example:
+	// s.Equal(expectedValue, actualValue)
Verification successful

Verify the function usage and add assertions.

The function calls to ExecuteContractTxMsg match the new signature consistently across the codebase.

  • msg_ethereum_tx_test.go
  • smart_contract_test.go

Consider adding assertions to validate the expected state after the transaction execution.

+	// Add assertions to validate the expected state after execution.
+	// Example:
+	// s.Equal(expectedValue, actualValue)
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify all function calls to `ExecuteContractTxMsg` match the new signature.

# Test: Search for the function usage. Expect: Only occurrences of the new signature.
rg --type go -A 5 $'ExecuteContractTxMsg'

Length of output: 2173

proto/eth/evm/v1/events.proto (3)

70-74: LGTM!

The EventTransfer message definition is correct and aligns with the intended functionality.


77-80: LGTM!

The EventContractDeployed message definition is correct and aligns with the intended functionality.


83-86: LGTM!

The EventContractExecuted message definition is correct and aligns with the intended functionality.

x/evm/evmtest/smart_contract.go (1)

32-42: LGTM!

The ArgsExecuteContract struct is well-defined and aligns with the intended functionality.

x/evm/evmtest/tx.go (1)

62-64: LGTM! But verify the function usage in the codebase.

The code changes are approved.

However, ensure that all function calls to NewEthTxMsgFromTxData match the new signature.

Verification successful

Verified: Function usage matches the new signature.

The function call to NewEthTxMsgFromTxData in msg_ethereum_tx_test.go has been correctly updated to match the new signature.

  • msg_ethereum_tx_test.go: Lines around the function call show all required parameters are included.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify all function calls to `NewEthTxMsgFromTxData` match the new signature.

# Test: Search for the function usage. Expect: Only occurrences of the new signature.
rg --type go -A 5 $'NewEthTxMsgFromTxData'

Length of output: 969


Script:

#!/bin/bash
# Description: Extract the complete function call to `NewEthTxMsgFromTxData` in `msg_ethereum_tx_test.go` to verify all parameters.

# Extract lines around the function call to ensure we capture the complete call.
rg --type go -A 10 -B 5 $'NewEthTxMsgFromTxData' x/evm/keeper/msg_ethereum_tx_test.go

Length of output: 492

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

33-41: LGTM! Improved gas limit handling and event assertions.

The changes enhance the test's robustness and coverage.


121-186: LGTM! Comprehensive test for contract execution.

The new test function enhances the test coverage for contract execution.


190-201: LGTM! Improved test case structure with txType.

The changes enhance readability and maintainability.

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

167-184: LGTM! Enhanced event emission logic for different transaction types.

The new event emission logic improves the overall event management within the application.

However, ensure that the new event types are correctly handled throughout the codebase.

Verification successful

LGTM! Enhanced event emission logic for different transaction types.

The new event emission logic improves the overall event management within the application. The new event types are correctly handled throughout the codebase, as evidenced by their definitions and corresponding test cases.

  • x/evm/events.pb.go: Definitions of EventContractDeployed, EventContractExecuted, and EventTransfer.
  • x/evm/keeper/msg_server.go: Emission of the new event types.
  • x/evm/keeper/msg_ethereum_tx_test.go: Test cases verifying the presence of the new event types.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage of new event types in the codebase.

# Test: Search for the new event types. Expect: Correct handling of new event types.
rg --type go -A 5 $'EventContractDeployed|EventContractExecuted|EventTransfer'

Length of output: 16605

CHANGELOG.md (1)

89-89: Changelog entry looks good.

The new entry is correctly formatted and provides sufficient information about the feature enhancement.

Comment on lines +77 to +79
innerTx.To = to
innerTx.Value = value
innerTx.Gas = gas
Copy link
Contributor

Choose a reason for hiding this comment

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

Reminder: Add tests for the new parameters.

The static analysis tools have flagged missing test coverage for the added lines.

Do you want me to generate the unit testing code or open a GitHub issue to track this task?

Also applies to: 86-88, 94-96

Tools
GitHub Check: codecov/patch

[warning] 77-79: x/evm/evmtest/tx.go#L77-L79
Added lines #L77 - L79 were not covered by tests

Comment on lines +51 to +54
testContract, err := embeds.SmartContract_TestERC20.Load()
if err != nil {
return nil, err
}
Copy link
Contributor

Choose a reason for hiding this comment

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

LGTM! But add tests for error handling.

The modification to use dynamic bytecode enhances flexibility. However, the error handling for loading the bytecode is not covered by tests.

Do you want me to generate the unit testing code for the error handling or open a GitHub issue to track this task?

Tools
GitHub Check: codecov/patch

[warning] 53-53: x/evm/evmtest/smart_contract.go#L53
Added line #L53 was not covered by tests

Comment on lines +90 to +113
func ExecuteContractTxMsg(args ArgsExecuteContract) (ethTxMsg *evm.MsgEthereumTx, err error) {
gasLimit := args.GasLimit
if gasLimit == nil {
gasLimit = new(big.Int).SetUint64(gethparams.TxGas)
}
gethTxExecuteContract := &gethcore.AccessListTx{
GasPrice: args.GasPrice,
Gas: gasLimit.Uint64(),
To: args.ContractAddress,
Data: args.Data,
Nonce: args.Nonce,
}
ethTx := gethcore.NewTx(gethTxExecuteContract)
ethTxMsg = new(evm.MsgEthereumTx)
err = ethTxMsg.FromEthereumTx(ethTx)
if err != nil {
return ethTxMsg, err
}
fromAcc := args.EthAcc
ethTxMsg.From = fromAcc.EthAddr.Hex()

gethSigner := fromAcc.GethSigner(args.EthChainIDInt)
keyringSigner := fromAcc.KeyringSigner
return ethTxMsg, ethTxMsg.Sign(gethSigner, keyringSigner)
Copy link
Contributor

Choose a reason for hiding this comment

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

LGTM! But add tests for error handling.

The function ExecuteContractTxMsg is well-structured. However, the error handling for transaction creation is not covered by tests.

Do you want me to generate the unit testing code for the error handling or open a GitHub issue to track this task?

Tools
GitHub Check: codecov/patch

[warning] 106-106: x/evm/evmtest/smart_contract.go#L106
Added line #L106 was not covered by tests

Copy link
Member

@Unique-Divine Unique-Divine left a comment

Choose a reason for hiding this comment

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

Left small improvement comment. Looks great overall

@onikonychev
Copy link
Contributor Author

Left small improvement comment. Looks great overall

@Unique-Divine you probably didn't finish the review as the comment is invisible.

Comment on lines 65 to 81
// Event "EventContractDeployed" must present
var sdkEvents = deps.Ctx.EventManager().Events()
contractDeployedEventType := "eth.evm.v1.EventContractDeployed"
err = testutil.AssertEventPresent(sdkEvents, contractDeployedEventType)
s.Require().NoError(err)

var contractDeployedEvent sdk.Event
for _, abciEvent := range sdkEvents {
if abciEvent.Type == contractDeployedEventType {
contractDeployedEvent = abciEvent
}
}
for _, err = range []error{
testutil.EventHasAttributeValue(contractDeployedEvent, "sender", ethAcc.EthAddr.String()),
testutil.EventHasAttributeValue(contractDeployedEvent, "contract_addr", resp.Logs[0].Address),
} {
s.Require().NoError(err)
Copy link
Member

@Unique-Divine Unique-Divine Jul 24, 2024

Choose a reason for hiding this comment

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

You can probably simplify this with
func RequireContainsTypedEvent(t require.TestingT, ctx sdk.Context, event proto.Message)

That way you can use the struct directly and won't need to put the type URL

Copy link
Contributor Author

Choose a reason for hiding this comment

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

What a handy method! Refactored everywhere (see commit) and added one forgotten event check.

Copy link
Contributor

@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: 0

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 9155dd0 and 123ae5d.

Files selected for processing (2)
  • x/evm/keeper/erc20_test.go (4 hunks)
  • x/evm/keeper/msg_ethereum_tx_test.go (5 hunks)
Additional comments not posted (8)
x/evm/keeper/msg_ethereum_tx_test.go (4)

67-75: Event Assertion Enhancement

The use of testutil.RequireContainsTypedEvent improves the readability and maintainability of event assertions.


98-104: Proper Error Handling for Insufficient Gas

The error handling for exceeding the gas limit is well-implemented, ensuring that the correct error is asserted.


161-169: Event Assertion Enhancement

The use of testutil.RequireContainsTypedEvent improves the readability and maintainability of event assertions.


225-234: Event Assertion Enhancement

The use of testutil.RequireContainsTypedEvent improves the readability and maintainability of event assertions.

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

107-116: Event Assertion Enhancement

The use of testutil.RequireContainsTypedEvent improves the readability and maintainability of event assertions.


248-258: Event Assertion Enhancement

The use of testutil.RequireContainsTypedEvent improves the readability and maintainability of event assertions.


368-378: Event Assertion Enhancement

The use of testutil.RequireContainsTypedEvent improves the readability and maintainability of event assertions.


Line range hint 1-1: Well-Structured ERC20 Operations Tests

The function is well-structured, with clear steps for setting up the test environment, performing operations, and asserting results.

@onikonychev onikonychev merged commit 197f652 into main Jul 24, 2024
17 checks passed
@onikonychev onikonychev deleted the on/evm-typed-events branch July 24, 2024 16:30
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.

3 participants