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(torii-graphql): add erc1155 to union #3057

Merged
merged 2 commits into from
Feb 21, 2025

Conversation

Larkooo
Copy link
Collaborator

@Larkooo Larkooo commented Feb 21, 2025

Summary by CodeRabbit

  • New Features
    • Added support for ERC1155 tokens, enabling enhanced token representation which includes comprehensive metadata handling.
    • Expanded token attribute and balance processing to integrate ERC1155 details alongside existing token standards.
    • Introduced new constants and mappings for ERC1155 token types and names in the GraphQL schema.

Copy link

coderabbitai bot commented Feb 21, 2025

Ohayo, sensei!

Walkthrough

This pull request introduces comprehensive support for ERC1155 tokens in the GraphQL layer. It adds two new constants for ERC1155 token identification, a static type mapping for ERC1155 token attributes, and new object definitions—including dedicated structs and enum variants—to handle ERC1155 tokens. Additionally, the token metadata parsing and resolver logic are updated in both token creation and token balance processes to correctly extract and map ERC1155-specific data from database rows.

Changes

Files Change Summary
…/graphql/src/constants.rs Added ERC1155_TYPE_NAME and ERC1155_TOKEN_NAME constants to define ERC1155 token identifiers.
…/graphql/src/mapping.rs Introduced ERC1155_TOKEN_TYPE_MAPPING using IndexMap to map ERC1155 token attributes to their corresponding type data.
…/graphql/src/object/erc/erc_token.rs, …/graphql/src/object/erc/token_balance.rs Extended token handling for ERC1155: added new structs (Erc1155TokenObject, Erc1155Token), updated the ErcTokenType enum with an ERC1155 variant, and modified methods to parse metadata and process ERC1155 tokens in both token creation and balance resolution.
…/graphql/src/schema.rs Included Erc1155TokenObject in the GraphQL schema and updated the erc_token_union to support the new ERC1155 type.

Possibly related PRs

  • test(torii-indexer): add tests for erc tokens  #3033: The changes in the main PR, which introduce new constants for ERC1155 tokens, are related to the retrieved PR that adds tests specifically for ERC1155 token operations, as both involve the ERC1155 token standard and its implementation.

Suggested reviewers

  • glihm (sensei)
✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

🪧 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. (Beta)
  • @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.

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

@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

🧹 Nitpick comments (7)
crates/torii/graphql/src/object/erc/erc_token.rs (6)

65-80: Ohayo sensei, new BasicObject looks great.

The Erc1155TokenObject structure parallels the pattern for other token objects. However, there's some duplication with the existing Erc20/Erc721. Consider a shared trait or macro if you'd like to reduce code repetition in the future.


111-123: Ohayo sensei, data fields look on point.

Erc1155Token fields match the specs for referencing metadata and are consistent with Erc20/Erc721. You might consider using numeric types for amount or token_id if there's a potential for numeric operations, but if your domain logic stores them as strings, this is fine.


161-184: Ohayo sensei, your to_field_value expansion is working well.

The approach for Erc1155 is in line with existing token logic. If you'd like to reduce duplication between Erc721 and Erc1155, consider extracting shared metadata logic into a helper function.


509-567: Ohayo sensei, ephemeral subscription logic is consistent.

This block for subscription updates is quite similar to Erc721. Reusing a helper that processes metadata might keep your code DRY and flexible.


637-679: Ohayo sensei, metadata extraction for ERC1155 is consistent.

Everything is in harmony with ERC721 parsing. If repetition becomes unmanageable, factor out a shared routine to parse token metadata.


681-683: Ohayo sensei, your unknown contract error path is safe.

Returning RowNotFound is straightforward, but you could consider a more explicit error (e.g. UnsupportedContractType) if you'd like more clarity.

crates/torii/graphql/src/object/erc/token_balance.rs (1)

216-271: Consider extracting duplicated ERC1155 token handling logic.

Ohayo sensei! The ERC1155 token handling logic is duplicated in both the subscription handler and connection output handler. Consider extracting this into a shared helper function to improve maintainability and reduce code duplication.

Here's a suggested implementation:

fn create_erc1155_token(row: &BalanceQueryResultRaw) -> ErcTokenType {
    let token_id = row.token_id.split(':').collect::<Vec<&str>>();
    assert!(token_id.len() == 2);

    let metadata_str = row.metadata.clone();
    let (
        metadata_str,
        metadata_name,
        metadata_description,
        metadata_attributes,
        image_path,
    ) = if metadata_str.is_empty() {
        (String::new(), None, None, None, String::new())
    } else {
        let metadata: serde_json::Value =
            serde_json::from_str(&metadata_str).expect("metadata is always json");
        let metadata_name = metadata.get("name")
            .map(|v| v.to_string().trim_matches('"').to_string());
        let metadata_description = metadata.get("description")
            .map(|v| v.to_string().trim_matches('"').to_string());
        let metadata_attributes = metadata.get("attributes")
            .map(|v| v.to_string().trim_matches('"').to_string());

        let image_path = format!("{}/{}", token_id.join("/"), "image");

        (
            metadata_str,
            metadata_name,
            metadata_description,
            metadata_attributes,
            image_path,
        )
    };

    let token_metadata = Erc1155Token {
        name: row.name.clone(),
        metadata: metadata_str,
        contract_address: row.contract_address.clone(),
        symbol: row.symbol.clone(),
        token_id: token_id[1].to_string(),
        amount: row.balance.clone(),
        metadata_name,
        metadata_description,
        metadata_attributes,
        image_path,
    };
    
    ErcTokenType::Erc1155(token_metadata)
}

Then use it in both places:

- // In subscription handler and connection output handler
- "erc1155" => {
-     // ... duplicated code ...
- }
+ "erc1155" => create_erc1155_token(&row),

Also applies to: 489-540

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f244197 and 75457eb.

📒 Files selected for processing (4)
  • crates/torii/graphql/src/constants.rs (2 hunks)
  • crates/torii/graphql/src/mapping.rs (1 hunks)
  • crates/torii/graphql/src/object/erc/erc_token.rs (6 hunks)
  • crates/torii/graphql/src/object/erc/token_balance.rs (3 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: docs
  • GitHub Check: ensure-wasm
  • GitHub Check: clippy
🔇 Additional comments (7)
crates/torii/graphql/src/object/erc/erc_token.rs (3)

11-11: Ohayo sensei, this addition is neat.

No issues with adding the use tracing::warn; import. This aligns with the usage in the unknown contract type handling.


15-20: Ohayo sensei, sweet expansions to coverage.

Adding the ERC1155 constants here is consistent. Everything is in line with existing patterns.


86-86: Ohayo sensei, the enum variant is well integrated.

This extension of ErcTokenType to include Erc1155 is consistent with the code's architecture.

crates/torii/graphql/src/constants.rs (2)

44-44: Ohayo sensei, your new constant is spiffy.

Defining ERC1155_TYPE_NAME is consistent with the naming convention for other ERC token types.


59-59: Ohayo sensei, your new token name constant looks good.

This addition aligns well with existing references for ERC1155 tokens. Perfect synergy.

crates/torii/graphql/src/mapping.rs (1)

180-192: Ohayo sensei, the new ERC1155 token type mapping is on point.

This complements the existing mappings for ERC20 and ERC721. Nicely consistent.

crates/torii/graphql/src/object/erc/token_balance.rs (1)

25-25: LGTM!

Ohayo! The import of Erc1155Token is correctly added alongside Erc721Token.

Comment on lines +232 to +233
serde_json::from_str(&metadata_str)
.expect("metadata is always json");
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Replace expect() with proper error handling.

Ohayo sensei! Using expect() for JSON parsing could cause panics in production. Consider using proper error handling instead.

Here's a suggested implementation:

- serde_json::from_str(&metadata_str).expect("metadata is always json");
+ serde_json::from_str(&metadata_str).map_err(|e| {
+     sqlx::Error::Protocol(format!("Failed to parse metadata JSON: {}", e))
+ })?;

Also applies to: 505-506

Comment on lines +217 to +219
let token_id =
row.token_id.split(':').collect::<Vec<&str>>();
assert!(token_id.len() == 2);
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Validate token ID format before splitting.

Ohayo sensei! The token ID splitting logic assumes a specific format without validation. Consider adding proper validation before splitting.

Here's a suggested implementation:

fn validate_and_split_token_id(token_id: &str) -> Result<Vec<&str>, sqlx::Error> {
    let parts: Vec<&str> = token_id.split(':').collect();
    if parts.len() != 2 {
        return Err(sqlx::Error::Protocol(
            format!("Invalid token ID format: {}. Expected format: contract_address:token_id", token_id)
        ));
    }
    Ok(parts)
}

Then use it in the code:

- let token_id = row.token_id.split(':').collect::<Vec<&str>>();
- assert!(token_id.len() == 2);
+ let token_id = validate_and_split_token_id(&row.token_id)?;

Also applies to: 490-492

Copy link

codecov bot commented Feb 21, 2025

Codecov Report

Attention: Patch coverage is 4.01786% with 215 lines in your changes missing coverage. Please review.

Project coverage is 57.46%. Comparing base (f244197) to head (af6e07a).
Report is 4 commits behind head on main.

Files with missing lines Patch % Lines
crates/torii/graphql/src/object/erc/erc_token.rs 4.83% 118 Missing ⚠️
...ates/torii/graphql/src/object/erc/token_balance.rs 0.00% 97 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3057      +/-   ##
==========================================
- Coverage   57.65%   57.46%   -0.20%     
==========================================
  Files         439      439              
  Lines       59437    59657     +220     
==========================================
+ Hits        34267    34279      +12     
- Misses      25170    25378     +208     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

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

🧹 Nitpick comments (1)
crates/torii/graphql/src/schema.rs (1)

145-148: Consider documenting the token type order, sensei! 📝

The token types in the union follow a specific order (ERC20 -> ERC721 -> ERC1155). While this works correctly, it would be helpful to document whether this order is significant for the application logic.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 75457eb and af6e07a.

📒 Files selected for processing (1)
  • crates/torii/graphql/src/schema.rs (3 hunks)
🔇 Additional comments (3)
crates/torii/graphql/src/schema.rs (3)

14-15: Ohayo! The import changes look great, sensei! 🎉

The imports are well-organized and correctly include the new ERC1155 token support.

Also applies to: 19-21


136-136: Nice work registering the ERC1155 object, sensei! ✨

The Erc1155TokenObject is properly registered as a Basic variant, maintaining consistency with other ERC token objects.


147-148: Excellent union type extension, sensei! 🌟

The ERC1155 type is properly added to the token union, enabling GraphQL queries to handle ERC1155 tokens alongside ERC20 and ERC721 tokens.

@Larkooo Larkooo enabled auto-merge (squash) February 21, 2025 16:13
@Larkooo Larkooo merged commit df7cec5 into dojoengine:main Feb 21, 2025
13 of 15 checks passed
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.

2 participants