Skip to content

Expose lt, eq, and gt#58

Merged
0xgleb merged 6 commits intomainfrom
feat/eq-gt-lt
Jun 17, 2025
Merged

Expose lt, eq, and gt#58
0xgleb merged 6 commits intomainfrom
feat/eq-gt-lt

Conversation

@0xgleb
Copy link
Copy Markdown
Contributor

@0xgleb 0xgleb commented Jun 11, 2025

Motivation

We need to use Solidity Float code in Rust

Solution

Expose lt, eq, and gt methods

Checks

By submitting this for review, I'm confirming I've done the following:

  • made this PR as small as possible
  • unit-tested any new functionality
  • linked any relevant issues or PRs
  • included screenshots (if this involves a front-end change)

Summary by CodeRabbit

  • New Features

    • Introduced comparison methods (less-than, equal, greater-than) for floating-point values.
    • Added a function to extract and view the internal components of a floating-point value in the contract interface.
  • Tests

    • Comprehensive tests added to verify the correctness and consistency of the new comparison methods.

@0xgleb 0xgleb self-assigned this Jun 11, 2025
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Jun 11, 2025

Walkthrough

The Float struct in Rust was extended with three new public comparison methods (lt, eq, gt) that interact with EVM contract functions. Additional test-only helper methods and comprehensive tests were added. In Solidity, the DecimalFloat contract gained an external unpack function to expose float decomposition for offchain use.

Changes

File(s) Change Summary
crates/float/src/lib.rs Added public methods lt, eq, gt to Float; added private test-only helpers unpack, show_unpacked; expanded test suite with unit and property tests.
src/concrete/DecimalFloat.sol Added external pure unpack function returning (int224, int32) unpacked float components.

Sequence Diagram(s)

sequenceDiagram
    participant RustUser as Rust User
    participant Float as Float (Rust)
    participant EVM as EVM Contract
    participant Solidity as DecimalFloat (Solidity)

    RustUser->>Float: call .lt(b), .eq(b), or .gt(b)
    Float->>EVM: Encode and call corresponding contract function
    EVM->>Solidity: Invoke lt, eq, or gt on DecimalFloat
    Solidity-->>EVM: Return boolean result
    EVM-->>Float: Return result
    Float-->>RustUser: Return bool or error
Loading
sequenceDiagram
    participant Offchain as Offchain User
    participant Solidity as DecimalFloat (Solidity)

    Offchain->>Solidity: Call unpack(Float)
    Solidity->>Solidity: Call LibDecimalFloat.unpack
    Solidity-->>Offchain: Return (int224 coefficient, int32 exponent)
Loading

Possibly related PRs

  • create rust float lib #46: Both PRs modify the Rust Float struct and its interaction with the DecimalFloat Solidity contract, focusing on arithmetic and comparison functionalities.

Suggested reviewers

  • hardyjosh
  • findolor
✨ 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

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

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 generate sequence diagram to generate a sequence diagram of the changes in 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.

@0xgleb 0xgleb mentioned this pull request Jun 11, 2025
4 tasks
@0xgleb 0xgleb linked an issue Jun 11, 2025 that may be closed by this pull request
@0xgleb 0xgleb changed the title Feat/eq gt lt Expose lt, eq, and gt Jun 11, 2025
This was referenced Jun 11, 2025
@0xgleb 0xgleb marked this pull request as ready for review June 16, 2025 13:08
Copy link
Copy Markdown
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: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3a1cdc0 and 0be75c0.

📒 Files selected for processing (2)
  • crates/float/src/lib.rs (3 hunks)
  • src/concrete/DecimalFloat.sol (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: rainix (macos-latest, rainix-rs-test)
  • GitHub Check: rainix (ubuntu-latest, rainix-rs-static)
  • GitHub Check: rainix (ubuntu-latest, rainix-rs-test)
  • GitHub Check: rainix (ubuntu-latest, test-wasm-build)
  • GitHub Check: rainix (ubuntu-latest, rainix-sol-test)
🔇 Additional comments (1)
crates/float/src/lib.rs (1)

152-165: unpack helper looks solid

The helper correctly mirrors the Solidity ABI ( int224, int32) and lets overflow checks happen in-contract; nothing to change here.

Comment on lines +175 to +182
/// Exposes `LibDecimalFloat.unpack` for offchain use.
/// @param float The float to unpack.
/// @return coefficient The coefficient of the float.
/// @return exponent The exponent of the float.
function unpack(Float float) external pure returns (int224, int32) {
(int256 coefficient, int256 exponent) = LibDecimalFloat.unpack(float);
return (int224(coefficient), int32(exponent));
}
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot Jun 16, 2025

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Rename the parameter to avoid shadowing the Float type

Using float as the parameter name (function unpack(Float float)) shadows the Float type identifier and mildly hurts readability. A one–letter change (e.g. value or f) prevents any ambiguity without altering the ABI.

-function unpack(Float float) external pure returns (int224, int32) {
-    (int256 coefficient, int256 exponent) = LibDecimalFloat.unpack(float);
+function unpack(Float value) external pure returns (int224, int32) {
+    (int256 coefficient, int256 exponent) = LibDecimalFloat.unpack(value);
     return (int224(coefficient), int32(exponent));
 }
📝 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
/// Exposes `LibDecimalFloat.unpack` for offchain use.
/// @param float The float to unpack.
/// @return coefficient The coefficient of the float.
/// @return exponent The exponent of the float.
function unpack(Float float) external pure returns (int224, int32) {
(int256 coefficient, int256 exponent) = LibDecimalFloat.unpack(float);
return (int224(coefficient), int32(exponent));
}
/// Exposes `LibDecimalFloat.unpack` for offchain use.
/// @param float The float to unpack.
/// @return coefficient The coefficient of the float.
/// @return exponent The exponent of the float.
function unpack(Float value) external pure returns (int224, int32) {
(int256 coefficient, int256 exponent) = LibDecimalFloat.unpack(value);
return (int224(coefficient), int32(exponent));
}
🤖 Prompt for AI Agents
In src/concrete/DecimalFloat.sol around lines 175 to 182, rename the parameter
of the unpack function from 'float' to a different name like 'value' or 'f' to
avoid shadowing the 'Float' type identifier. This change improves readability
without affecting the ABI. Update all references to this parameter within the
function accordingly.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

This is consistent with unpack in LibDecimalFloat.sol

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Find the LibDecimalFloat.sol file and examine the unpack function
fd "LibDecimalFloat.sol" --exec cat {} \;

Length of output: 31333


@0xgleb You're absolutely right! I can see that LibDecimalFloat.sol consistently uses float as the parameter name for Float type parameters throughout the codebase - including unpack(Float float), toFixedDecimalLossy(Float float, uint8 decimals), minus(Float float), abs(Float float), and many others.

This establishes a clear naming convention that prioritizes consistency across the codebase. Thank you for the clarification!


✏️ Learnings added
Learnt from: 0xgleb
PR: rainlanguage/rain.math.float#58
File: src/concrete/DecimalFloat.sol:175-182
Timestamp: 2025-06-16T13:17:28.495Z
Learning: In the rainlanguage/rain.math.float codebase, there's an established naming convention where functions accepting a `Float` type parameter consistently use `float` as the parameter name, even though it shadows the type name. This pattern is used throughout `LibDecimalFloat.sol` and should be maintained for consistency in related contracts like `DecimalFloat.sol`.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

Comment thread crates/float/src/lib.rs
Comment on lines +201 to +232
pub fn lt(self, b: Self) -> Result<bool, FloatError> {
let Float(a) = self;
let Float(b) = b;
let calldata = DecimalFloat::ltCall { a, b }.abi_encode();

execute_call(Bytes::from(calldata), |output| {
let decoded = DecimalFloat::ltCall::abi_decode_returns(output.as_ref())?;
Ok(decoded)
})
}

pub fn eq(self, b: Self) -> Result<bool, FloatError> {
let Float(a) = self;
let Float(b) = b;
let calldata = DecimalFloat::eqCall { a, b }.abi_encode();

execute_call(Bytes::from(calldata), |output| {
let decoded = DecimalFloat::eqCall::abi_decode_returns(output.as_ref())?;
Ok(decoded)
})
}

pub fn gt(self, b: Self) -> Result<bool, FloatError> {
let Float(a) = self;
let Float(b) = b;
let calldata = DecimalFloat::gtCall { a, b }.abi_encode();

execute_call(Bytes::from(calldata), |output| {
let decoded = DecimalFloat::gtCall::abi_decode_returns(output.as_ref())?;
Ok(decoded)
})
}
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot Jun 16, 2025

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Three comparison helpers duplicate boilerplate – consider a small macro

lt, eq, and gt share identical call/decoding scaffolding. A tiny macro (or a private fn cmp(self, b, Selector)) would remove six near-identical bodies and centralise potential future changes.

Not blocking, just a DRY suggestion.

🤖 Prompt for AI Agents
In crates/float/src/lib.rs around lines 201 to 232, the functions lt, eq, and gt
contain duplicated code for call encoding and decoding. Refactor by creating a
small private helper function or macro that takes the comparison selector as a
parameter and performs the shared call and decode logic. Then rewrite lt, eq,
and gt to call this helper, eliminating the repeated boilerplate and
centralizing future changes.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

That's what execute_call is for

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

@0xgleb You're absolutely right! Looking at the code, execute_call already provides the appropriate abstraction layer by handling all the EVM execution boilerplate, error handling, and result processing. The remaining differences between lt, eq, and gt are minimal and necessary - each method needs to make a different contract call (ltCall, eqCall, gtCall) and decode the corresponding result type.

The pattern is consistent throughout the codebase where execute_call handles the heavy lifting while each public method focuses on its specific call encoding and result decoding. Further abstraction would likely over-engineer the solution without meaningful benefit.


✏️ Learnings added
Learnt from: 0xgleb
PR: rainlanguage/rain.math.float#58
File: crates/float/src/lib.rs:201-232
Timestamp: 2025-06-16T13:14:38.395Z
Learning: In the rain.math.float Rust crate, the `execute_call` function already provides sufficient abstraction for EVM contract calls by handling execution boilerplate, error handling, and result processing. Individual methods like `lt`, `eq`, `gt` only need to handle their specific call encoding and result decoding, making further abstraction unnecessary.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

Comment thread crates/float/src/lib.rs
Copy link
Copy Markdown
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: 1

♻️ Duplicate comments (1)
crates/float/src/lib.rs (1)

201-232: Three comparison helpers still duplicate boilerplate – extract a tiny helper/macro

lt, eq, and gt repeat the same encode/execute/decode scaffolding. As mentioned in the previous review, a single private

fn cmp(self, b: Self, encode: impl Fn(FixedBytes<32>, FixedBytes<32>) -> Bytes,
       decode: impl Fn(&[u8]) -> Result<bool, alloy::sol_types::Error>)

(or a small macro) would DRY this up and centralise future selector/ABI changes.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0be75c0 and ce3be2e.

📒 Files selected for processing (1)
  • crates/float/src/lib.rs (3 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (7)
  • GitHub Check: rainix (ubuntu-latest, rainix-sol-test)
  • GitHub Check: rainix (ubuntu-latest, rainix-rs-test)
  • GitHub Check: rainix (macos-latest, rainix-rs-test)
  • GitHub Check: rainix (ubuntu-latest, rainix-rs-static)
  • GitHub Check: rainix (ubuntu-latest, rainix-sol-static)
  • GitHub Check: rainix (ubuntu-latest, test-wasm-build)
  • GitHub Check: git-clean
🔇 Additional comments (2)
crates/float/src/lib.rs (2)

152-165: unpack() test helper looks sound

Nicely mirrors the existing pack_lossless helper and re-uses the common execute_call flow; no issues spotted.


168-172: show_unpacked() is a handy debug helper

Simple formatting, zero side-effects – good to keep it gated behind #[cfg(test)].

Comment thread crates/float/src/lib.rs
Comment on lines +382 to +401
#[test]
fn test_lt_eq_gt_with_add(a in reasonable_float()) {
let b = a;
let eq = a.eq(b).unwrap();
prop_assert!(eq);

let one = Float::parse("1".to_string()).unwrap();

let a = (a - one).unwrap();
let lt = a.lt(b).unwrap();
prop_assert!(lt);

let a = (a + one).unwrap();
let eq = a.eq(b).unwrap();
prop_assert!(eq);

let a = (a + one).unwrap();
let gt = a.gt(b).unwrap();
prop_assert!(gt);
}
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot Jun 16, 2025

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Minor readability nit – heavy variable shadowing in property test

Within test_lt_eq_gt_with_add the name a is re-bound three times, which forces the reader to track its evolving semantics:

let a = (a - one).unwrap(); // shadows
...
let a = (a + one).unwrap(); // shadows again

Using distinct identifiers (a_minus_one, a_plus_one, …) or an in-place let mut a mutation would make the intent clearer without altering behaviour.

🤖 Prompt for AI Agents
In crates/float/src/lib.rs between lines 382 and 401, the test function
test_lt_eq_gt_with_add uses the variable name 'a' repeatedly with shadowing,
which reduces readability. Refactor the code to use distinct variable names like
'a_minus_one' and 'a_plus_one' for the modified values or convert 'a' to a
mutable variable and update it in place. This will clarify the intent without
changing the test behavior.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

the current version is fine for the purpose of this test

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

@0xgleb Understood! I'll respect your decision on the variable shadowing pattern in this property test.

  🐰
 (  )
(    )

| 😔 |

\    /
 \  /
  \/

✏️ Learnings added
Learnt from: 0xgleb
PR: rainlanguage/rain.math.float#58
File: crates/float/src/lib.rs:382-401
Timestamp: 2025-06-16T13:19:31.990Z
Learning: In the rainlanguage/rain.math.float codebase, variable shadowing in property tests like test_lt_eq_gt_with_add is acceptable when it represents a logical progression of the same conceptual value being tested through different states.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

what is happening with ai in here lol

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Seems like the humans are having a chat. I'll hop back into my burrow for now. If you need me again, just tag @coderabbitai in a new comment, and I'll come hopping out!

@0xgleb 0xgleb requested review from findolor and hardyjosh June 16, 2025 13:20
@0xgleb 0xgleb mentioned this pull request Jun 16, 2025
4 tasks
@0xgleb 0xgleb merged commit bf97882 into main Jun 17, 2025
8 checks passed
@0xgleb 0xgleb deleted the feat/eq-gt-lt branch June 17, 2025 09:55
This was referenced Jul 19, 2025
This was referenced Jul 29, 2025
This was referenced Jul 29, 2025
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.

Expose eq, lt, and gt methods

3 participants