Skip to content

Conversation

JasoonS
Copy link
Contributor

@JasoonS JasoonS commented Aug 26, 2025

Enhance Quantity deserialization to accept numeric values

Updated the QuantityVisitor to handle both hex strings and numeric values (u64 and i64) for deserialization. Added tests to verify the correct handling of numeric JSON values.

Summary by CodeRabbit

  • Improvements

    • Quantity fields in JSON now accept numeric values (positive integers) in addition to hex strings for more flexible input.
    • Better error messaging when an invalid numeric value (e.g., negative) is provided.
    • Maintains backward compatibility with existing hex-based inputs.
  • Tests

    • Added tests validating numeric and hex deserialization, canonicalization of values, and error handling for invalid inputs.

Enhance Quantity deserialization to accept numeric values

Updated the QuantityVisitor to handle both hex strings and numeric values (u64 and i64) for deserialization. Added tests to verify the correct handling of numeric JSON values.
Copy link

coderabbitai bot commented Aug 26, 2025

Walkthrough

Quantity deserialization in hypersync-format now accepts numeric JSON tokens (u64/i64) in addition to hex strings via deserialize_any; Visitor handlers for u64 and i64 canonicalize big-endian bytes (i64 negatives error) and produce a Quantity. Cargo package version bumped.

Changes

Cohort / File(s) Summary
Quantity deserialization
hypersync-format/src/types/quantity.rs
Deserialize impl switched to deserialize_any; added visit_u64 and visit_i64 handlers; expectation message updated; numeric values converted to big-endian bytes and canonicalized; negative i64 rejected; tests added for numeric u64/i64.
Crate metadata
hypersync-format/Cargo.toml
Bumped crate version from 0.5.3 to 0.5.4 (no dependency changes).

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant JSON as JSON Input
  participant Serde as Serde Deserializer
  participant Visitor as QuantityVisitor
  participant Qty as Quantity

  JSON->>Serde: Token (hex string | u64 | i64)
  Serde->>Visitor: deserialize_any(...)
  alt Hex string
    Visitor->>Visitor: decode hex -> canonicalize bytes
    Visitor->>Qty: construct Quantity
  else u64
    Visitor->>Visitor: u64.to_be_bytes() -> canonicalize bytes
    Visitor->>Qty: construct Quantity
  else i64
    alt negative
      Visitor-->>Serde: error ("expected non-negative")
    else non-negative
      Visitor->>Visitor: cast to u64 -> to_be_bytes() -> canonicalize bytes
      Visitor->>Qty: construct Quantity
    end
  end
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Possibly related PRs

Poem

A nibble of hex, a crunch of ten,
I hop through bytes and back again.
u64 seeds, i64 sprout,
But negatives? I nose them out.
Canonical trails I gladly tread—
Quantity snug in its burrowed bed. 🐇💾

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.


📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 014a6fb and 99bdd6e.

📒 Files selected for processing (1)
  • hypersync-format/Cargo.toml (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • hypersync-format/Cargo.toml
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: test_dev
  • GitHub Check: test_release
✨ Finishing Touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch block-number-int

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.
    • 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.
  • 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 the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

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

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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.

@JasoonS JasoonS marked this pull request as ready for review August 26, 2025 10:43
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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (3)
hypersync-format/src/types/quantity.rs (3)

27-34: ethers feature: U256 -> Quantity construction writes into a zero-length buffer

Box::new([]) creates an empty slice; to_big_endian writes nothing, yielding an empty Quantity, violating invariants elsewhere. Construct into a fixed 32-byte buffer and canonicalize.

 #[cfg(feature = "ethers")]
 impl From<ethabi::ethereum_types::U256> for Quantity {
     fn from(value: ethabi::ethereum_types::U256) -> Self {
-        let mut buf = Box::new([]);
-        value.to_big_endian(buf.as_mut());
-        Self(buf)
+        let mut tmp = [0u8; 32];
+        value.to_big_endian(&mut tmp);
+        // Strip leading zeros to maintain canonical representation
+        let start = tmp.iter().position(|&b| b != 0).unwrap_or(tmp.len() - 1);
+        Self(tmp[start..].into())
     }
 }

49-56: ethers feature: U64 -> Quantity has the same zero-length buffer issue

Same fix as U256 with an 8-byte buffer.

 #[cfg(feature = "ethers")]
 impl From<ethabi::ethereum_types::U64> for Quantity {
     fn from(value: ethabi::ethereum_types::U64) -> Self {
-        let mut buf = Box::new([]);
-        value.to_big_endian(buf.as_mut());
-        Self(buf)
+        let mut tmp = [0u8; 8];
+        value.to_big_endian(&mut tmp);
+        let start = tmp.iter().position(|&b| b != 0).unwrap_or(tmp.len() - 1);
+        Self(tmp[start..].into())
     }
 }

62-69: ethers feature: Wrong length check for U64 (should be 8, not 32)

This allows oversize inputs to slip through or erroneously rejects correct ones depending on context. Fix to 8 bytes for U64.

-        if value.0.len() > 32 {
+        if value.0.len() > 8 {
             return Err(());
         }
🧹 Nitpick comments (4)
hypersync-format/src/types/quantity.rs (4)

98-98: Tighten the expectation message to reflect unsigned-only acceptance

We reject negative i64s below, so the expectation can be more precise: “hex string or non-negative integer.” Small wording tweak improves error clarity.

Apply:

-        formatter.write_str("hex string or numeric value for a quantity")
+        formatter.write_str("hex string (0x…) or non-negative integer for a quantity")

110-117: Avoid heap allocation in visit_u64; build a canonical slice and use From<&[u8]>

Current code allocates a Vec and then canonicalizes. We can canonicalize by slicing the stack array produced by to_be_bytes(), cutting a heap alloc and a copy.

-        // Convert the integer to big-endian bytes and canonicalize
-        let buf = canonicalize_bytes(value.to_be_bytes().to_vec());
-        Ok(Quantity::from(buf))
+        // Convert to big-endian bytes, slice off leading zeros, construct from slice
+        let bytes = value.to_be_bytes();
+        let start = bytes.iter().position(|&b| b != 0).unwrap_or(bytes.len() - 1);
+        Ok(Quantity::from(&bytes[start..]))

119-129: Use structured Serde error for negatives and avoid allocation (mirror u64 path)

Return E::invalid_value with Unexpected::Signed for better diagnostics, and avoid Vec allocation like in visit_u64.

-        if value < 0 {
-            return Err(E::custom("negative quantity not allowed"));
-        }
-        let unsigned = value as u64;
-        let buf = canonicalize_bytes(unsigned.to_be_bytes().to_vec());
-        Ok(Quantity::from(buf))
+        if value < 0 {
+            return Err(E::invalid_value(de::Unexpected::Signed(value), &"non-negative integer quantity"));
+        }
+        let unsigned = value as u64;
+        let bytes = unsigned.to_be_bytes();
+        let start = bytes.iter().position(|&b| b != 0).unwrap_or(bytes.len() - 1);
+        Ok(Quantity::from(&bytes[start..]))

301-306: Add a negative i64 test and a boundary test

We reject negatives; add an assertion to lock this in. Also add i64::MAX to verify upper-bound handling.

     #[test]
     fn test_deserialize_numeric_i64() {
         assert_de_tokens(&Quantity::from(hex!("66a7c725")), &[Token::I64(0x66a7c725)]);
         assert_de_tokens(&Quantity::from(vec![0]), &[Token::I64(0)]);
         assert_de_tokens(&Quantity::from(hex!("01")), &[Token::I64(1)]);
     }
+
+    #[test]
+    fn test_deserialize_numeric_i64_negative_rejected() {
+        use serde_test::assert_de_tokens_error;
+        assert_de_tokens_error::<Quantity>(&[Token::I64(-1)], "non-negative integer");
+    }
+
+    #[test]
+    fn test_deserialize_numeric_i64_max() {
+        assert_de_tokens(
+            &Quantity::from(i64::MAX.to_be_bytes().as_slice()),
+            &[Token::I64(i64::MAX)],
+        );
+    }
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 9ebffa2 and 014a6fb.

📒 Files selected for processing (1)
  • hypersync-format/src/types/quantity.rs (3 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
hypersync-format/src/types/quantity.rs (2)
hypersync-format/src/types/util.rs (1)
  • canonicalize_bytes (11-22)
hypersync-format/src/types/fixed_size_data.rs (1)
  • deserialize (173-178)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: lint
  • GitHub Check: test_release
  • GitHub Check: test_dev
🔇 Additional comments (2)
hypersync-format/src/types/quantity.rs (2)

137-139: Switch to deserialize_any is appropriate and scoped

This enables U64/I64 tokens without widening acceptance to floats or other token kinds (no visit_f64 implemented), matching the PR goal. Looks good.


293-299: Good coverage for U64 numeric deserialization

Solid checks for zero, one, and a representative larger value. This validates canonicalization and acceptance of numeric JSON tokens.

Comment on lines +137 to +138
// Accept either hex strings (0x...) or numeric JSON values
deserializer.deserialize_any(QuantityVisitor)
Copy link
Contributor

Choose a reason for hiding this comment

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

Not a big deal but probably would be better to call deserialize_str first, match and if there's an error call deserialize_u64

Then there's no overhead in it just running all the visit functions. You control the entry point. And you don't need visit_i64 for eg.

Copy link
Contributor

Choose a reason for hiding this comment

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

I actually think this would be a worthwhile thing to do since we use quantity for a lot of fields

Copy link
Contributor

@JonoPrest JonoPrest left a comment

Choose a reason for hiding this comment

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

Non-blocking comments, thanks!

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