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

test(torii): add metadata to erc1155 and update #3054

Merged
merged 6 commits into from
Feb 21, 2025

Conversation

Larkooo
Copy link
Collaborator

@Larkooo Larkooo commented Feb 20, 2025

Summary by CodeRabbit

  • New Features
    • Introduced a token URI retrieval feature that returns a JSON-formatted URI based on token ID, enhancing the presentation of token imagery.
    • Added functions for updating token metadata for both ERC721 and ERC1155 tokens, improving metadata management across token standards.
  • Tests
    • Added a new asynchronous test for updating token metadata in the ERC1155 contract, expanding test coverage.

Copy link

coderabbitai bot commented Feb 20, 2025

Ohayo, sensei! Here’s the updated overview of the changes:

Walkthrough

A new external function token_uri has been introduced in the ERC1155 contract implementation. This function accepts a token_id and returns a ByteArray that contains a JSON string with an image URL generated using the current block number. Existing functions such as mint, transfer_from, and batch operations remain unchanged. Additionally, the manifest_dev.json file has been updated to reflect new contract deployments and added functions for both ERC721Token and ERC1155Token.

Changes

File Change Summary
examples/spawn-and-move/src/…/erc1155.cairo Added a new external function token_uri to the ExternalImpl of ExternalTrait, which returns a JSON string encapsulated in a ByteArray; other functions remain unchanged.
examples/spawn-and-move/manifest_dev.json Updated ERC721Token and ERC1155Token with new class hashes, addresses, and functions for updating token metadata; added new struct for handling updates.
crates/torii/indexer/src/test.rs Introduced an asynchronous test function test_update_token_metadata_erc1155 to validate the updating of token metadata for the ERC1155 contract.
crates/torii/sqlite/src/utils.rs Modified sanitize_json_string to simplify and enhance the logic for handling JSON strings, focusing on quotes and backslashes.

Sequence Diagram(s)

sequenceDiagram
    participant C as Client
    participant E as ERC1155 Contract
    C->>E: Call token_uri(token_id)
    E->>E: Build JSON with image URL using block number
    E-->>C: Return ByteArray with JSON
Loading

Possibly related PRs

Suggested reviewers

  • glihm
✨ 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: 0

🧹 Nitpick comments (2)
examples/spawn-and-move/src/externals/erc1155.cairo (2)

64-68: Ohayo! Consider adding token_id validation, sensei! 🎭

The token URI implementation is creative, using DiceBear for generating unique avatars. However, we should validate that the token_id exists before generating the URI.

    #[external(v0)]
    fn token_uri(ref self: ContractState, token_id: u256) -> ByteArray {
+       // Verify token exists
+       assert(self.erc1155.balance_of(starknet::get_caller_address(), token_id) > 0, 'Token does not exist');
        let tx_hash = starknet::get_tx_info().transaction_hash;
        format!("{{ \"image\": \"https://api.dicebear.com/9.x/lorelei-neutral/png?seed={:x}\" }}", tx_hash)
    }

60-63:

❓ Verification inconclusive

Arigato for the clear testing disclaimer, sensei! 🛡️

The comment clearly indicates this is for testing. For production, consider:

  1. Rate limiting token_uri calls
  2. Adding access control for minting
  3. Implementing proper safe transfer checks

Let's verify the contract's testing nature is documented in the repository:


🏁 Script executed:

#!/bin/bash
# Search for testing/example documentation
rg -i "test|example" README.md

Length of output: 509


Ohayo, sensei! Thanks for the clear testing disclaimer.

Your inline comment in examples/spawn-and-move/src/externals/erc1155.cairo (lines 60-63) clearly marks this implementation as for testing and quick minting only. However, our search in the project README didn't reveal additional documentation supporting this testing-only use. Please ensure that this intended use case is well communicated across the repository to avoid any deployment mix-ups later.

For production, consider:

  • Rate limiting token_uri calls to mitigate abuse.
  • Adding access control for minting to secure token issuance.
  • Implementing proper safe transfer checks to strengthen overall security.
📜 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 0604b32.

⛔ Files ignored due to path filters (1)
  • examples/spawn-and-move/Scarb.lock is excluded by !**/*.lock
📒 Files selected for processing (1)
  • examples/spawn-and-move/src/externals/erc1155.cairo (1 hunks)
🔇 Additional comments (1)
examples/spawn-and-move/src/externals/erc1155.cairo (1)

10-10: Sugoi implementation of ERC4906 integration, sensei! ✨

The ERC4906 component integration for metadata updates pairs nicely with the new token_uri function. This provides a complete solution for token metadata management.

Also applies to: 15-15, 23-23

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

🧹 Nitpick comments (2)
examples/spawn-and-move/src/externals/erc1155.cairo (1)

64-64: Ohayo sensei! Let's add some documentation for our new function.

Consider adding natspec documentation to match other functions and comply with standards:

 #[external(v0)]
+/// @notice Get the URI for a given token ID
+/// @dev Returns a data URI containing token metadata in JSON format
+/// @param token_id The ID of the token to query
+/// @return ByteArray containing the token's metadata URI
 fn token_uri(ref self: ContractState, token_id: u256) -> ByteArray {
examples/spawn-and-move/manifest_dev.json (1)

3918-3929: Ohayo, sensei! update_tokens_metadata Function Enhancement for ERC1155Token

The addition of the update_tokens_metadata function, which accepts an array (via the Span struct) of token IDs, is a nice touch for flexibility. It would be beneficial to have unit tests covering this new functionality if you haven’t added them already.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0604b32 and 876df17.

📒 Files selected for processing (2)
  • examples/spawn-and-move/manifest_dev.json (12 hunks)
  • examples/spawn-and-move/src/externals/erc1155.cairo (1 hunks)
🔇 Additional comments (7)
examples/spawn-and-move/manifest_dev.json (7)

2426-2429: Ohayo, sensei! External Contract Details for ERC721Token Updated

The new class_hash and address values for the ERC721Token (instance "Badge") are now updated. Please confirm that these values match your deployed contract details to ensure proper external integration.


2457-2506: Ohayo, sensei! Adding Metadata Update Functions for ERC721Token

Nice work on adding the new metadata update functions to the ERC721Token ABI – namely, update_token_metadata, update_batch_token_metadata, and update_tokens_metadata. The input types (using core::integer::u256 and the new Span struct) look correct, but please double-check that these ABI entries fully match your contract implementation and caller expectations.


3771-3774: Ohayo, sensei! ERC1155Token External Contract Details Updated

The ERC1155Token (instance "Rewards") now reflects updated class_hash and address values. Ensure these values are correctly deployed and that all downstream references are updated accordingly.


3790-3807: Ohayo, sensei! Updated ByteArray Struct in ERC1155Token ABI

The updated definition for core::byte_array::ByteArray in this segment now uses the expected members. Verify that this new structure is consistent with how the token_uri function will assemble and return its JSON metadata payload.


3808-3823: Ohayo, sensei! New token_uri Function Added for ERC1155Token

The introduction of the token_uri function here is great. It accepts a token_id and returns a ByteArray containing the JSON metadata, as intended. Everything appears to be in order with the function signature and return type.


3891-3901: Ohayo, sensei! New update_token_metadata Function for ERC1155Token

The new function update_token_metadata in the ERC1155Token section is a solid addition for updating individual token metadata. Please ensure that the metadata handling logic on the contract side (not shown here) is consistent with this ABI.


3903-3917: Ohayo, sensei! Batch Metadata Update Function for ERC1155Token

The implementation of update_batch_token_metadata to allow bulk updates is well integrated. Make sure the semantics of the "from" and "to" token IDs cover all edge cases, particularly with sequential token IDs.

Comment on lines 64 to 68
#[external(v0)]
fn token_uri(ref self: ContractState, token_id: u256) -> ByteArray {
let tx_hash = starknet::get_tx_info().transaction_hash;
format!("data:application/json,{{ \"image\": \"https://api.dicebear.com/9.x/lorelei-neutral/png?seed={}\" }}", tx_hash)
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Ohayo sensei! Let's make the token URI implementation more robust.

The current implementation has a few concerns:

  1. Using transaction hash means the same token could have different URIs in different transactions
  2. External dependency on dicebear service could be risky if the service changes/goes down

Consider this improved implementation:

 #[external(v0)]
 fn token_uri(ref self: ContractState, token_id: u256) -> ByteArray {
+    // Validate token exists
+    assert(self.erc1155._exists(token_id), 'ERC1155: URI query for nonexistent token');
+    
+    // Use token_id for deterministic image generation
     let tx_hash = starknet::get_tx_info().transaction_hash;
-    format!("data:application/json,{{ \"image\": \"https://api.dicebear.com/9.x/lorelei-neutral/png?seed={}\" }}", tx_hash)
+    format!(
+        "data:application/json,{{\"name\":\"Token #{}\",\"image\":\"https://api.dicebear.com/9.x/lorelei-neutral/png?seed={}\"}}", 
+        token_id, 
+        token_id
+    )
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
#[external(v0)]
fn token_uri(ref self: ContractState, token_id: u256) -> ByteArray {
let tx_hash = starknet::get_tx_info().transaction_hash;
format!("data:application/json,{{ \"image\": \"https://api.dicebear.com/9.x/lorelei-neutral/png?seed={}\" }}", tx_hash)
}
#[external(v0)]
fn token_uri(ref self: ContractState, token_id: u256) -> ByteArray {
// Validate token exists
assert(self.erc1155._exists(token_id), 'ERC1155: URI query for nonexistent token');
// Use token_id for deterministic image generation
let tx_hash = starknet::get_tx_info().transaction_hash;
format!(
"data:application/json,{{\"name\":\"Token #{}\",\"image\":\"https://api.dicebear.com/9.x/lorelei-neutral/png?seed={}\"}}",
token_id,
token_id
)
}

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 (8)
crates/torii/sqlite/src/utils.rs (3)

63-63: Ohayo sensei! Consider using a more descriptive variable name.

The variable name backslash_count could be more descriptive to indicate its purpose in tracking escape sequences.

-    let mut backslash_count = 0;
+    let mut escape_sequence_count = 0;

75-78: Consider extracting backslash handling into a separate function.

The backslash handling logic could be clearer if extracted into a dedicated function.

+    fn handle_backslash(count: &mut usize) -> char {
+        *count += 1;
+        '\\'
+    }

79-104: Consider simplifying the nested conditionals.

The deep nesting of conditionals makes the code harder to follow. Consider extracting the quote handling logic into a separate function.

+    fn handle_quote(chars: &mut std::iter::Peekable<std::str::Chars>, backslash_count: usize) -> (bool, String) {
+        if backslash_count % 2 != 0 {
+            return (true, "\"".to_string());
+        }
+        
+        let mut temp_chars = chars.clone();
+        while let Some(&next_c) = temp_chars.peek() {
+            if !next_c.is_whitespace() {
+                return match next_c {
+                    ':' | ',' | '}' => (false, "\"".to_string()),
+                    _ => (true, "\\\"".to_string())
+                };
+            }
+            temp_chars.next();
+        }
+        (false, "\"".to_string())
+    }
crates/torii/indexer/src/test.rs (3)

933-935: Ohayo sensei! The test function looks good but could use more documentation.

Consider adding a doc comment explaining the test's purpose and expected behavior.

+/// Tests the ERC1155 token metadata update functionality:
+/// 1. Mints a new token
+/// 2. Updates its metadata
+/// 3. Verifies the metadata contains the correct image URL

966-976: Consider adding assertions for successful minting.

The test should verify that the token was minted successfully before proceeding with metadata updates.

     TransactionWaiter::new(tx.transaction_hash, &provider).await.unwrap();
+
+    // Verify successful minting
+    let balance = provider
+        .call(
+            Call {
+                to: rewards_address,
+                selector: get_selector_from_name("balance_of").unwrap(),
+                calldata: vec![account.address(), Felt::from(1), Felt::ZERO],
+            },
+            BlockId::Latest,
+        )
+        .await
+        .unwrap();
+    assert_eq!(balance[0], Felt::from(1), "Token should be minted with amount 1");

1025-1028: Add more comprehensive metadata verification.

The test only checks for the image URL. Consider verifying other metadata fields as well.

     assert!(token.metadata.contains(&format!(
         "\"image\": \"https://api.dicebear.com/9.x/lorelei-neutral/png?seed={}\"",
         block_number
     )));
+    // Verify other metadata fields
+    assert!(token.metadata.contains("\"name\""));
+    assert!(token.metadata.contains("\"description\""));
+    assert!(token.metadata.contains("\"attributes\""));
examples/spawn-and-move/manifest_dev.json (2)

2457-2506: Ohayo sensei! New metadata update functions added for ERC721Token.
The ABI now includes additional functions: update_token_metadata, update_batch_token_metadata, and update_tokens_metadata along with the associated struct for core::array::Span::<core::integer::u256>. These additions align with enriched contract capabilities. Please ensure that these function signatures match the corresponding implementation in the contract and that comprehensive tests are in place for metadata updates.


3890-3929: Ohayo sensei! Added metadata update functions for ERC1155Token.
The ABI now includes update_token_metadata, update_batch_token_metadata, and update_tokens_metadata for ERC1155Token. These functions are analogous to those for ERC721Token and aim to improve metadata management. Please confirm that the newly added functions’ inputs and state mutability are in line with your design intentions and that you have tests covering various metadata update scenarios.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 876df17 and 0774918.

⛔ Files ignored due to path filters (4)
  • crates/torii/types-test/Scarb.lock is excluded by !**/*.lock
  • examples/simple/Scarb.lock is excluded by !**/*.lock
  • spawn-and-move-db.tar.gz is excluded by !**/*.gz
  • types-test-db.tar.gz is excluded by !**/*.gz
📒 Files selected for processing (4)
  • crates/torii/indexer/src/test.rs (1 hunks)
  • crates/torii/sqlite/src/utils.rs (1 hunks)
  • examples/spawn-and-move/manifest_dev.json (12 hunks)
  • examples/spawn-and-move/src/externals/erc1155.cairo (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • examples/spawn-and-move/src/externals/erc1155.cairo
🔇 Additional comments (3)
examples/spawn-and-move/manifest_dev.json (3)

2426-2429: Ohayo sensei! Review the updated ERC721Token deployment.
The external contract definition for ERC721Token now shows an updated class_hash and address (notice the tilde markers on these lines). Please double-check that these new values exactly match the intended deployed contract details.


3771-3774: Ohayo sensei! Confirm the updated ERC1155Token deployment details.
The external contract for ERC1155Token now shows an updated class_hash and address (with tilde markers on these lines) and uses the instance name "Rewards". Please verify that these deployment details are consistent with your intended network configuration.


3790-3823: Ohayo sensei! New token_uri function detected in ERC1155Token ABI.
A new function token_uri(token_id: core::integer::u256) has been added that returns a core::byte_array::ByteArray. This is expected to wrap a JSON string containing an image URL based on the token ID. Ensure that the implementation in the corresponding Cairo contract (e.g. in erc1155.cairo) matches this ABI and that the JSON structure is validated in your tests.

@Larkooo Larkooo enabled auto-merge (squash) February 21, 2025 05:08
Copy link

codecov bot commented Feb 21, 2025

Codecov Report

Attention: Patch coverage is 97.70992% with 3 lines in your changes missing coverage. Please review.

Project coverage is 57.82%. Comparing base (f244197) to head (7ca0847).
Report is 3 commits behind head on main.

Files with missing lines Patch % Lines
crates/torii/sqlite/src/utils.rs 91.66% 3 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3054      +/-   ##
==========================================
+ Coverage   57.65%   57.82%   +0.16%     
==========================================
  Files         439      439              
  Lines       59437    59543     +106     
==========================================
+ Hits        34267    34429     +162     
+ Misses      25170    25114      -56     

☔ 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 (2)
crates/torii/sqlite/src/utils.rs (2)

74-77: Consider adding a maximum backslash limit.

While the backslash counting logic is correct, extremely long sequences of backslashes could lead to unnecessary counting. Consider adding a reasonable limit.

 } else if c == '\\' {
+    if backslash_count < 1000 {  // Arbitrary limit
         backslash_count += 1;
+    }
     result.push('\\');

271-281: Test coverage looks good!

The test cases cover both unescaped and properly escaped scenarios.

However, consider adding these edge cases:

  1. Empty strings
  2. Multiple consecutive unescaped quotes
  3. Maximum backslash sequences
+    #[test]
+    fn test_sanitize_json_string_edge_cases() {
+        // Empty string
+        assert_eq!(sanitize_json_string(r#""""#), r#""""#);
+        
+        // Multiple consecutive unescaped quotes
+        assert_eq!(
+            sanitize_json_string(r#"{"key":""value""}"#),
+            r#"{"key":"\"value\""}"#
+        );
+        
+        // Many backslashes
+        assert_eq!(
+            sanitize_json_string(r#"{"key":"\\\\"}"#),
+            r#"{"key":"\\\\"}"#
+        );
+    }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between dec7146 and 7ca0847.

📒 Files selected for processing (1)
  • crates/torii/sqlite/src/utils.rs (1 hunks)
🔇 Additional comments (4)
crates/torii/sqlite/src/utils.rs (4)

63-63: Ohayo! Nice addition of backslash tracking, sensei!

The introduction of backslash_count improves escape sequence handling.


66-73: LGTM! Clean handling of non-string context.

The logic for handling characters outside of string context is clear and straightforward.


78-103: Excellent string boundary detection, sensei!

The logic for detecting string boundaries by looking ahead at non-whitespace characters is robust and handles edge cases well.


104-112: Clean state management.

Good practice resetting the backslash count after processing each character.

@Larkooo Larkooo merged commit c48484e into dojoengine:main Feb 21, 2025
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