Skip to content

Conversation

@rouzwelt
Copy link
Collaborator

@rouzwelt rouzwelt commented Jan 31, 2026

Motivation

This PR updates the logic for getting market price quote, where if the unit quote size (1 unit token) fails to give any valid result, partial sizes are also tried.

Solution

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

    • Fallback market-price flow: if an initial price lookup fails, an alternative trade-size-based lookup is attempted.
    • Added an option to treat computed trade sizes as absolute, influencing how fallback sizes are chosen.
  • Bug Fixes

    • Improved price-retrieval robustness by attempting a secondary, size-aware price check when the primary attempt fails.
  • Tests

    • Expanded tests covering single-size, partial-size (happy/unhappy) and fallback scenarios.

✏️ Tip: You can customize this high-level summary in your review settings.

@rouzwelt rouzwelt self-assigned this Jan 31, 2026
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jan 31, 2026

Walkthrough

Added an absolute parameter to router.findLargestTradeSize (threaded RainSolverRouter → SushiRouter) and made SharedState.getMarketPrice asynchronous with a fallback retry that calls findLargestTradeSize when the initial price fetch fails.

Changes

Cohort / File(s) Summary
Router method & tests
src/router/router.ts, src/router/router.test.ts
Extended findLargestTradeSize signature to accept optional absolute (default false); updated test invocation to pass the flag.
Sushi router logic
src/router/sushi/index.ts
Added absolute parameter and a new branch: when absolute is true and route is feasible, push computed max input into results and adjust maximumInput without doing the price-comparison path.
SharedState async fallback & tests
src/state/index.ts, src/state/index.test.ts
Converted getMarketPrice to async; on initial failure, call router.findLargestTradeSize(..., absolute) to compute a partial amountIn and retry getMarketPrice; expanded tests for happy/partial/unhappy scenarios and added mock findLargestTradeSize.

Sequence Diagram(s)

sequenceDiagram
    participant Client as Client
    participant SS as SharedState
    participant Router as Router
    participant Sushi as SushiRouter

    Client->>SS: getMarketPrice(fromToken, toToken, ...)
    SS->>SS: amountIn = 1 unit
    SS->>Router: getMarketPrice(amountIn, gasPrice, routeType, skipFetch)
    Router->>Sushi: getMarketPrice(...)
    Sushi-->>Router: result (isOk? true/false)
    Router-->>SS: result

    alt initial fetch failed
        SS->>Router: findLargestTradeSize(orderDetails, toToken, fromToken, maximumInputFixed, gasPrice, routeType, absolute)
        Router->>Sushi: findLargestTradeSize(...)
        Sushi-->>Router: partialAmountIn (bigint | undefined)
        Router-->>SS: partialAmountIn

        alt partialAmountIn present
            SS->>Router: getMarketPrice(partialAmountIn, gasPrice, routeType, skipFetch)
            Router->>Sushi: getMarketPrice(...)
            Sushi-->>Router: retry result
            Router-->>SS: retry result
        end
    end

    SS-->>Client: final result
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested labels

bug

Suggested reviewers

  • Siddharth2207
  • hardyjosh
🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately captures the main objective of the changeset: implementing partial quote size functionality for market price queries in the Sushi router.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch 2026-01031-market-price-quote-partial-size

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

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

Copy link
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: 2

🤖 Fix all issues with AI agents
In `@src/state/index.test.ts`:
- Line 444: The test case title in the unit test function it("should call
getMarketPrice with correct params for partial size uhappy all", ...) contains a
typo; change "uhappy" to "unhappy" in the it(...) description in
src/state/index.test.ts so the test reads it("should call getMarketPrice with
correct params for partial size unhappy all", ...); leave the test
implementation and identifiers (e.g., the it(...) call and any describe blocks)
unchanged.

In `@src/state/index.ts`:
- Around line 332-340: Explain in a short inline comment above the
partialAmountIn call that the mocked orderDetails ({ takeOrder: { quote: {
ratio: 0n } } } as any) is safe because findLargestTradeSize is invoked with
absolute=true, which bypasses any ratio-based comparisons; reference
findLargestTradeSize, partialAmountIn and the absolute=true flag so future
readers know why the cast/as any is acceptable and cannot affect logic.

Copy link
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

🤖 Fix all issues with AI agents
In `@src/state/index.ts`:
- Around line 341-352: The retry path currently treats any non-bigint
partialAmountIn as a guard but misses zero or negative bigints; add a check for
partialAmountIn <= 0n before calling this.router.getMarketPrice and skip the
retry (return result or handle as before) to avoid calling getMarketPrice with
amountIn=0n; locate the variable partialAmountIn (and the call to
this.router.getMarketPrice) and short-circuit when partialAmountIn is not a
positive bigint.

Comment on lines +341 to 352
if (typeof partialAmountIn !== "bigint") {
return result;
}
const partialResult = await this.router.getMarketPrice({
fromToken,
toToken,
blockNumber,
gasPrice: this.gasPrice,
amountIn: parseUnits("1", fromToken.decimals),
amountIn: partialAmountIn,
sushiRouteType: this.appOptions.route,
skipFetch: !!skipFetch,
});
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Guard against zero-sized partial quotes.
If findLargestTradeSize returns 0n (or another non-positive sentinel), the retry will call getMarketPrice with amountIn=0n, which is likely invalid. Add a non‑positive guard to avoid unnecessary/erroneous calls.

🔧 Suggested fix
-        if (typeof partialAmountIn !== "bigint") {
+        if (typeof partialAmountIn !== "bigint" || partialAmountIn <= 0n) {
             return result;
         }
📝 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
if (typeof partialAmountIn !== "bigint") {
return result;
}
const partialResult = await this.router.getMarketPrice({
fromToken,
toToken,
blockNumber,
gasPrice: this.gasPrice,
amountIn: parseUnits("1", fromToken.decimals),
amountIn: partialAmountIn,
sushiRouteType: this.appOptions.route,
skipFetch: !!skipFetch,
});
if (typeof partialAmountIn !== "bigint" || partialAmountIn <= 0n) {
return result;
}
const partialResult = await this.router.getMarketPrice({
fromToken,
toToken,
blockNumber,
gasPrice: this.gasPrice,
amountIn: partialAmountIn,
sushiRouteType: this.appOptions.route,
skipFetch: !!skipFetch,
});
🤖 Prompt for AI Agents
In `@src/state/index.ts` around lines 341 - 352, The retry path currently treats
any non-bigint partialAmountIn as a guard but misses zero or negative bigints;
add a check for partialAmountIn <= 0n before calling this.router.getMarketPrice
and skip the retry (return result or handle as before) to avoid calling
getMarketPrice with amountIn=0n; locate the variable partialAmountIn (and the
call to this.router.getMarketPrice) and short-circuit when partialAmountIn is
not a positive bigint.

@hardyjosh hardyjosh merged commit b368d78 into master Jan 31, 2026
5 of 13 checks passed
@github-actions
Copy link
Contributor

@coderabbitai assess this PR size classification for the totality of the PR with the following criterias and report it in your comment:

S/M/L PR Classification Guidelines:

This guide helps classify merged pull requests by effort and complexity rather than just line count. The goal is to assess the difficulty and scope of changes after they have been completed.

Small (S)

Characteristics:

  • Simple bug fixes, typos, or minor refactoring
  • Single-purpose changes affecting 1-2 files
  • Documentation updates
  • Configuration tweaks
  • Changes that require minimal context to review

Review Effort: Would have taken 5-10 minutes

Examples:

  • Fix typo in variable name
  • Update README with new instructions
  • Adjust configuration values
  • Simple one-line bug fixes
  • Import statement cleanup

Medium (M)

Characteristics:

  • Feature additions or enhancements
  • Refactoring that touches multiple files but maintains existing behavior
  • Breaking changes with backward compatibility
  • Changes requiring some domain knowledge to review

Review Effort: Would have taken 15-30 minutes

Examples:

  • Add new feature or component
  • Refactor common utility functions
  • Update dependencies with minor breaking changes
  • Add new component with tests
  • Performance optimizations
  • More complex bug fixes

Large (L)

Characteristics:

  • Major feature implementations
  • Breaking changes or API redesigns
  • Complex refactoring across multiple modules
  • New architectural patterns or significant design changes
  • Changes requiring deep context and multiple review rounds

Review Effort: Would have taken 45+ minutes

Examples:

  • Complete new feature with frontend/backend changes
  • Protocol upgrades or breaking changes
  • Major architectural refactoring
  • Framework or technology upgrades

Additional Factors to Consider

When deciding between sizes, also consider:

  • Test coverage impact: More comprehensive test changes lean toward larger classification
  • Risk level: Changes to critical systems bump up a size category
  • Team familiarity: Novel patterns or technologies increase complexity

Notes:

  • the assessment must be for the totality of the PR, that means comparing the base branch to the last commit of the PR
  • the assessment output must be exactly one of: S, M or L (single-line comment) in format of: SIZE={S/M/L}
  • do not include any additional text, only the size classification
  • your assessment comment must not include tips or additional sections
  • do NOT tag me or anyone else on your comment

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jan 31, 2026

The author of this PR is on the CodeRabbit Free Plan. In order to use the Chat feature, please upgrade the PR author to CodeRabbit Pro by visiting https://app.coderabbit.ai/login.

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.

3 participants