Skip to content

feat(evm): debug_traceBlockByNumber results for funtoken creation txs #2224

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

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from

Conversation

onikonychev
Copy link
Contributor

@onikonychev onikonychev commented Mar 5, 2025

Produces traces for the debug_traceBlockByNumber query when tx is a creation of a funtoken from coin. Used by indexers to track erc20 funtoken contracts.

curl --location 'http://127.0.0.1:8545' \
--header 'Content-Type: application/json' \
--data '{
    "id": 1,
    "jsonrpc": "2.0",
    "method": "debug_traceBlockByNumber",
    "params": [
        "0x42",
        {
            "tracer": "callTracer",
            "timeout": "30s",
            "tracerConfig": { "onlyTopCall": true }
        }
        ]
}' | jq

Output looks like

{
  "jsonrpc": "2.0",
  "id": 1,
  "result": [
    {
      "result": {
        "from": "0x603871c2ddd41c26ee77495e2e31e6de7f9957e0",
        "gas": "0x34a79c",
        "gasUsed": "0x23203b",
        "input": "0x60806040523480156...",
        "output": "0x6080604052348015...",
        "to": "0x7d4b7b8ca7e1a24928bb96d59249c7a5bd1dfbe6",
        "type": "CREATE",
        "value": "0x0"
      }
    }
  ]
}

Copy link
Contributor

coderabbitai bot commented Mar 5, 2025

📝 Walkthrough

Walkthrough

This update documents and implements a new feature for debugging fun token creation transactions in the Ethereum Virtual Machine. A new changelog entry has been added, and several backend components now handle fun token creation. Enhancements include additional test suite variables and functions to deploy and verify fun token contracts, changes in the tracing logic to capture and process fun token events, and new event parsing logic in the events module.

Changes

File(s) Summary
CHANGELOG.md Added a new "Unreleased" entry for the feature: feat(evm): debug_traceBlockByNumber results for funtoken creation txs referencing PR #2224.
eth/.../backend_suite_test.go Added global variables, a WaitForSDKTx helper, and CreateNibiFunToken method; updated SetupSuite to deploy a fun token contract during tests.
eth/.../tracing.go Introduced a new slice to track fun token creation transactions, added generateFunTokenCreationTraces and getErc20ContractMetadata methods, and updated TraceBlock.
eth/.../tracing_test.go Added the TestTraceBlockFunTokenCreated function and a helper AssertTraceFunTokenCreated to validate that fun token creation traces are correctly produced.
x/evm/events.go Defined a new constant TypeUrlEventFunTokenCreated and a function EventFunTokenCreatedFromABCIEvent to parse fun token creation events from ABCI events.

Sequence Diagram(s)

sequenceDiagram
  participant TS as Test Suite
  participant BE as RPC Backend
  participant TC as Trace Creator
  participant ERC20 as ERC20 Metadata

  TS->>BE: Call CreateNibiFunToken()
  BE->>TS: Broadcast fun token creation tx
  TS->>BE: WaitForSDKTx(txHash)
  BE->>BE: Process block with TraceBlock
  BE->>TC: generateFunTokenCreationTraces(...txIndexes)
  TC->>ERC20: getErc20ContractMetadata(contractAddr, height)
  ERC20-->>TC: Return metadata
  TC-->>BE: Return assembled trace
  BE-->>TS: Output fun token creation trace result
Loading

Possibly related PRs

Suggested labels

x: evm

Suggested reviewers

  • Unique-Divine
  • k-yang

Poem

I'm a clever rabbit, hopping along the code lane,
Debugging fun tokens with a skip and a playful strain.
Traces and events now dance in neat array,
As tests sing success, making errors scurry away.
With a twitch of my nose and a hop so light,
I celebrate these changes through the day and night!
🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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>, please review it.
    • 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 gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @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 using 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 generate docstrings to generate docstrings for this 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.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

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.

@onikonychev onikonychev marked this pull request as ready for review March 5, 2025 18:32
@onikonychev onikonychev requested a review from a team as a code owner March 5, 2025 18:32
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

🧹 Nitpick comments (4)
eth/rpc/backend/tracing_test.go (1)

102-112: Test covers single transaction scenario well.
The new TestTraceBlockFunTokenCreated method correctly retrieves a block and verifies that only one fun token creation trace is found. As a future improvement, consider testing multiple fun token creation transactions in the same block to ensure robust coverage.

eth/rpc/backend/tracing.go (1)

281-344: Trace generation for funtoken creation is well-structured.

  1. Fetching block results, iterating only over the relevant tx indices, and extracting EventFunTokenCreated are logically grouped.
  2. Properly constructing a “CREATE” trace with from/to addresses, gas usage, input data, and output code helps indexers.
  3. Error handling ensures partial failures don’t terminate the entire operation.

Consider adding logs or counters for how many traces were successfully generated vs. skipped to further aid debugging.

eth/rpc/backend/backend_suite_test.go (2)

210-232: New utility function for waiting on SDK transactions.

The WaitForSDKTx function follows a similar pattern to the existing WaitForReceipt function, with appropriate timeout handling. The error handling approach, which checks if the error message contains "not found", is a reasonable way to distinguish between temporary and permanent errors.

Consider using a more robust approach for error type identification if the SDK provides one, as string matching can be brittle if error message formats change:

- if !strings.Contains(err.Error(), "not found") {
+ // If the SDK provides error types or constants for this specific error:
+ if errors.Is(err, sdk.ErrTxNotFound) {  // Example, use actual SDK error type if available

313-335: Well-implemented fun token creation method with proper error handling.

The CreateNibiFunToken method follows a clear approach:

  1. Gets the current nonce
  2. Broadcasts a message to create a fun token
  3. Waits for transaction confirmation
  4. Extracts the fun token contract address from events

The error handling is robust with appropriate assertions, including verification that the fun token contract address was successfully extracted.

Consider adding more context to error messages for better debugging:

- s.Require().NoError(err)
+ s.Require().NoError(err, "Failed to broadcast CreateFunToken message")

- s.Require().NoError(err)
+ s.Require().NoError(err, "Failed to wait for fun token creation transaction")
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 93f8495 and 10f549f.

📒 Files selected for processing (5)
  • CHANGELOG.md (1 hunks)
  • eth/rpc/backend/backend_suite_test.go (5 hunks)
  • eth/rpc/backend/tracing.go (5 hunks)
  • eth/rpc/backend/tracing_test.go (2 hunks)
  • x/evm/events.go (2 hunks)
🔇 Additional comments (13)
CHANGELOG.md (1)

44-44: Documented feature addition looks good.
This changelog entry succinctly references PR #2224 and aligns with the existing format.

x/evm/events.go (2)

25-26: Constant naming aligns with existing patterns.
Introducing TypeUrlEventFunTokenCreated for fun token creation event is consistent with the established naming convention (e.g., TypeUrlEventBlockBloom, TypeUrlEventTxLog).


108-120: Event parsing method is consistent and clear.
The function EventFunTokenCreatedFromABCIEvent matches existing event-parsing patterns, including error handling for parse failures. Overall, the approach is coherent and maintainable.

eth/rpc/backend/tracing_test.go (1)

147-154: Validation checks are appropriate.
AssertTraceFunTokenCreated properly enforces that the trace is "CREATE"-typed, directed from the EVM module address to the fun token contract, with expected zero value, and non-empty input/output fields. The checks are clear and thorough.

eth/rpc/backend/tracing.go (5)

8-17: Imports are organized properly.
Adding "strings" plus references to rpc, evm, and embeds is necessary for the new features. No issues noted.


156-157: Enables tracking of funtoken creation transactions.
Declaring funTokenCreationTxIndexes as an []int allows for indexing transactions that trigger fun token creation. This is a straightforward approach for capturing relevant txs.


168-173: Good branching for specialized message type.
Placing a check for MsgCreateFunToken within the standard transaction loop is concise and avoids separate routing. Validating FromBankDenom ensures correct identification of creation requests.


219-226: Conditional trace generation is performant.
Appending fun token creation traces only when the tracer is "callTracer" avoids unnecessary overhead for other modes. This is efficient and preserves existing behavior for other trace types.


346-385: Metadata retrieval approach is effective.
The new getErc20ContractMetadata method uses existing contract calls for “name”, “symbol”, and “decimals”, returning them for trace composition. Input packing via the ERC20Minter ABI is correct. Ensure tests exist for scenarios where token contracts fail to respond or return malformed data.

eth/rpc/backend/backend_suite_test.go (4)

8-8: Import added for error message handling.

The strings package is appropriately added to support error message parsing in the new WaitForSDKTx function.


59-62: New global variables for fun token information follow existing patterns.

These variables are well-named and consistent with the existing patterns in the file, where similar global variables are used for transfer transactions and contract deployments.


125-127: Consistent test setup with existing pattern.

The addition of fun token creation in SetupSuite follows the same pattern as the existing test contract deployment, maintaining consistency in the test setup flow.


327-332:

✅ Verification successful

Verify the event type checking is resilient to changes.

The code looks for events of type evm.TypeUrlEventFunTokenCreated to extract the contract address. Ensure this event type is stable and won't change, or that tests will be updated if it does.


🏁 Script executed:

#!/bin/bash
# Check if the event type constant is defined in the EVM package
grep -r "TypeUrlEventFunTokenCreated" ./x/evm/

Length of output: 311


Event Type Constant Stability Verification

The event type constant evm.TypeUrlEventFunTokenCreated is defined in ./x/evm/events.go as "eth.evm.v1.EventFunTokenCreated" and is used consistently, including in error handling. This indicates that the event type checking is currently stable. However, please ensure that any future changes to this constant are accompanied by corresponding updates in the tests to preserve the intended behavior.

  • Confirmed constant definition in ./x/evm/events.go.
  • Suggest reviewing related tests if any modifications to the event type occur.

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

🧹 Nitpick comments (3)
eth/rpc/backend/tracing.go (3)

299-306: Consider enhancing error reporting for event parsing.

When parsing the EventFunTokenCreated event fails, the code logs the error but continues to the next event. While this approach keeps the tracing process resilient, consider adding more context to the error message to assist with debugging.

-					b.logger.Error("failed to parse FunTokenCreated event", "error", err.Error())
+					b.logger.Error("failed to parse FunTokenCreated event", "error", err.Error(), "height", height, "txIndex", index, "eventType", event.Type)

323-327: Consider caching contract bytecode retrieval.

The code retrieves contract bytecode individually for each fun token creation trace. For blocks with multiple fun token creations, this could lead to redundant RPC calls if the same contract pattern is deployed multiple times.

Consider implementing a simple in-memory cache for the duration of trace generation to avoid duplicate GetCode calls for identical contracts within the same block.


346-386: Well-implemented ERC20 metadata retrieval.

The function correctly:

  1. Prepares method inputs for standard ERC20 interface calls
  2. Makes call requests at the correct block height
  3. Properly unpacks returned values
  4. Initializes default values and handles errors appropriately

Consider adding a timeout or context with deadline to prevent potential hanging when calling unresponsive or malicious contracts. This could be implemented by adding a context parameter or using a context with timeout in the DoCall method.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 10f549f and f5665b3.

📒 Files selected for processing (1)
  • eth/rpc/backend/tracing.go (5 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: e2e-evm
🔇 Additional comments (7)
eth/rpc/backend/tracing.go (7)

8-8: Appropriate imports added for the new functionality.

The additional imports are necessary for supporting the new fun token tracing functionality:

  • strings package for string manipulation in trace construction
  • Updated Nibiru imports to access required EVM functionality
  • hexutil for encoding data in the trace output

Also applies to: 10-12, 17-17


156-156: Well-placed tracking variable for fun token creation transactions.

The funTokenCreationTxIndexes slice is correctly initialized to collect transaction indices that create fun tokens, which will be used later to generate EVM-compatible traces.


168-174: Good special case handling for MsgCreateFunToken.

The implementation correctly identifies and tracks fun token creation transactions that convert from bank denominations (coins) to ERC20 tokens. This aligns with the PR objectives to support indexers that need to track these specific transactions.


219-226: Effective integration of fun token creation traces.

The implementation conditionally appends fun token creation traces when:

  1. Fun token creation transactions exist in the block
  2. The tracer is specifically set to "callTracer"

This ensures traces are only generated when needed and in the appropriate format expected by EVM tools and indexers.


329-341: Trace output format correctly follows EVM conventions.

The trace output format properly follows EVM conventions with:

  • Standard fields like from, to, gas, gasUsed, input, output, type, and value
  • Appropriate hexadecimal encoding for numeric values
  • Lowercase addresses as per Ethereum conventions
  • Correct transaction type ("CREATE") for contract deployment

331-338: Good use of standardized field formatting.

The trace output correctly uses:

  • strings.ToLower() for Ethereum addresses to maintain case consistency
  • hexutil.EncodeUint64() for gas values to ensure proper hex formatting with "0x" prefix
  • hexutil.Encode() for binary data like contract input
  • Explicit "0x0" for zero value transfers

These details ensure compatibility with EVM tooling that expects standardized formats.


282-344:

❓ Verification inconclusive

Comprehensive trace generation for fun token creation transactions.

The generateFunTokenCreationTraces function properly:

  1. Fetches block results for the specified height
  2. Processes each fun token creation transaction
  3. Extracts EventFunTokenCreated events
  4. Retrieves ERC20 metadata (name, symbol, decimals)
  5. Constructs standard EVM trace outputs

The error handling is robust with appropriate logging, allowing the process to continue even if individual trace generation fails.

Let's verify that the trace format matches what EVM-compatible tools expect:


🏁 Script executed:

#!/bin/bash
# Description: Check if the trace result structure matches the format expected by EVM debuggers/indexers

# Search for similar trace result structures in the codebase to confirm consistency
rg -A 10 "TxTraceResult.*Result.*map\[string\]interface" --type go

Length of output: 68


Please manually verify the EVM trace structure.
The generateFunTokenCreationTraces function appears to correctly:

  • Fetch block results.
  • Process fun token creation transactions.
  • Extract EventFunTokenCreated events.
  • Retrieve and pack ERC20 metadata.
  • Assemble and return the trace results with the expected fields (e.g., "from", "to", "gas", "gasUsed", "input", "output", "type", and "value").

However, the automated search for trace structure patterns using rg did not return any output. This result is inconclusive regarding whether the produced trace result format is fully compliant with what EVM-compatible tools expect. Please manually verify that the trace result structure (a map[string]interface{}) adheres to the EVM trace format requirements.

@onikonychev onikonychev marked this pull request as draft March 6, 2025 15:11
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.

1 participant