Skip to content

Fix/uniswap tickmath rounding [WIP don't merge]#73

Open
rdave8 wants to merge 2 commits into
mainfrom
fix/uniswap-tickmath-rounding
Open

Fix/uniswap tickmath rounding [WIP don't merge]#73
rdave8 wants to merge 2 commits into
mainfrom
fix/uniswap-tickmath-rounding

Conversation

@rdave8

@rdave8 rdave8 commented Jul 17, 2026

Copy link
Copy Markdown
Contributor

Summary by CodeRabbit

  • New Features

    • Expanded supported price and tick ranges, now covering approximately (1e-6) to (1e6).
    • Added stricter validation for maker price ranges, including protocol bounds, tick alignment, and valid lower/upper ordering.
  • Bug Fixes

    • Improved tick-based price calculations to use protocol-compatible rounding, providing more accurate boundary results.
  • Tests

    • Added coverage for expanded boundaries, alignment behavior, invalid ranges, and exact boundary calculations.

@coderabbitai

coderabbitai Bot commented Jul 17, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

The PR widens protocol price and tick bounds, updates tick square-root rounding, adjusts boundary tests, and centralizes maker price-to-tick conversion and validation in maker_ticks_from_prices.

Changes

Protocol tick and price bounds

Layer / File(s) Summary
Protocol bounds and tick rounding
src/constants.rs, src/math/tick.rs, src/convert.rs
Protocol bounds now target approximately 1e-61e6, tick conversion rounds up to match protocol behavior, and boundary tests use the updated constants and exact tick outputs.

Maker order validation

Layer / File(s) Summary
Maker tick conversion and validation
src/client/trades.rs
maker_ticks_from_prices aligns maker prices to ticks, validates bounds and ordering, and is used by open_maker; unit tests cover valid and invalid ranges.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Possibly related PRs

Suggested reviewers: praz314159

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately highlights the main change: Uniswap TickMath rounding behavior was fixed.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/uniswap-tickmath-rounding

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/client/trades.rs`:
- Around line 99-106: Validate that price_lower is strictly less than
price_upper before converting or aligning ticks in the surrounding trade range
logic. Return the existing invalid-range error for equal or reversed prices,
while preserving the current tick-bound checks; add regression coverage for
equal and reversed prices that fall within a single tick.

In `@src/convert.rs`:
- Around line 590-593: Update the minimum-price test around
price_to_sqrt_price_x96(1e-6) to assert the conversion succeeds and its value
equals MIN_SQRT_PRICE_X96, ensuring rounding produces the protocol minimum
rather than a lower truncated value.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: bd98caa7-cf10-44cb-b3f1-16c001f62de2

📥 Commits

Reviewing files that changed from the base of the PR and between e6aaa24 and 3907ad4.

📒 Files selected for processing (4)
  • src/client/trades.rs
  • src/constants.rs
  • src/convert.rs
  • src/math/tick.rs

Comment thread src/client/trades.rs
Comment on lines +99 to +106
let tick_lower = align_tick_down(price_to_tick(price_lower)?, TICK_SPACING);
let tick_upper = align_tick_up(price_to_tick(price_upper)?, TICK_SPACING);

if tick_lower < MIN_TICK || tick_upper > MAX_TICK || tick_lower >= tick_upper {
return Err(ValidationError::InvalidTickRange {
lower: tick_lower,
upper: tick_upper,
});

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Validate caller price ordering before widening ticks.

Equal—or reversed—prices that round to the same unaligned tick can become align_down(t) < align_up(t) and pass this check, opening an unintended range. Reject price_lower >= price_upper before alignment, and add a regression test using equal and reversed prices within one tick.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/client/trades.rs` around lines 99 - 106, Validate that price_lower is
strictly less than price_upper before converting or aligning ticks in the
surrounding trade range logic. Return the existing invalid-range error for equal
or reversed prices, while preserving the current tick-bound checks; add
regression coverage for equal and reversed prices that fall within a single
tick.

Comment thread src/convert.rs
Comment on lines +590 to 593
// 1e-6 is the protocol's minimum starting price.
let result = price_to_sqrt_price_x96(1e-6);
assert!(result.is_ok());
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Make the minimum-price conversion round up and assert the protocol value.

At 1e-6, even ideal scaling produces floor(Q96 / 1000), while MIN_SQRT_PRICE_X96 is one unit higher; Q96 % 1000 = 336. The current test therefore passes while the produced value is below the factory minimum.

Proposed fix
-    Ok((scaled_int * Q96) / BIGINT_1E6)
+    Ok((scaled_int * Q96 + BIGINT_1E6 - U256::from(1u8)) / BIGINT_1E6)
-use crate::constants::{MAX_SQRT_PRICE_X96, Q96_PRECISION};
+use crate::constants::{MAX_SQRT_PRICE_X96, MIN_SQRT_PRICE_X96, Q96_PRECISION};

 fn price_very_small_works() {
-    let result = price_to_sqrt_price_x96(1e-6);
-    assert!(result.is_ok());
+    assert_eq!(
+        price_to_sqrt_price_x96(1e-6).unwrap(),
+        MIN_SQRT_PRICE_X96
+    );
 }
📝 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
// 1e-6 is the protocol's minimum starting price.
let result = price_to_sqrt_price_x96(1e-6);
assert!(result.is_ok());
}
// 1e-6 is the protocol's minimum starting price.
assert_eq!(
price_to_sqrt_price_x96(1e-6).unwrap(),
MIN_SQRT_PRICE_X96
);
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/convert.rs` around lines 590 - 593, Update the minimum-price test around
price_to_sqrt_price_x96(1e-6) to assert the conversion succeeds and its value
equals MIN_SQRT_PRICE_X96, ensuring rounding produces the protocol minimum
rather than a lower truncated value.

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