Skip to content

handle negative amountOut error#452

Merged
rouzwelt merged 1 commit into
masterfrom
2026-06-23-handle-negative-amount-out-error
Jun 27, 2026
Merged

handle negative amountOut error#452
rouzwelt merged 1 commit into
masterfrom
2026-06-23-handle-negative-amount-out-error

Conversation

@rouzwelt

@rouzwelt rouzwelt commented Jun 23, 2026

Copy link
Copy Markdown
Collaborator

Motivation

handles negative amountOut error from router

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

  • Bug Fixes

    • Enhanced error detection and handling for invalid routing calculations that produce negative outputs.
    • Improved router reset mechanism to clear cached data more reliably when edge cases occur.
  • Refactor

    • Optimized internal calculation logic for better performance.

@rouzwelt rouzwelt self-assigned this Jun 23, 2026
@rouzwelt rouzwelt added the bug Something isn't working label Jun 23, 2026
@coderabbitai

coderabbitai Bot commented Jun 23, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

SushiRouter gains a signalReset flag, set to true when findBestRoute detects a negative amountOutBI and returns a new NegativeOutput error, then cleared in reset(). The CLI's maybeResetDataFetcher() now triggers a reset on this signal in addition to the time-based interval. Separately, probablyPicksFrom drops an intermediate variable in its offset calculation.

Changes

Sushi Router Negative Output Detection and Reset Signaling

Layer / File(s) Summary
NegativeOutput error type, signalReset flag, and findBestRoute detection
src/router/sushi/error.ts, src/router/sushi/index.ts
Adds NegativeOutput to SushiRouterErrorType enum; adds signalReset = false property to SushiRouter; updates findBestRoute to set signalReset = true and return a SushiRouterError(NegativeOutput) when route.amountOutBI < 0n; clears signalReset in reset() after dataFetcher re-initialization.
CLI reset guard integration
src/cli/index.ts
maybeResetDataFetcher() condition expanded to also trigger when this.state.router.sushi?.signalReset is true, alongside the existing time-interval check.

probablyPicksFrom Offset Refactor

Layer / File(s) Summary
Offset calculation cleanup
src/rpc/helpers.ts
Removes the intermediate weightsSlice variable; offset is now computed by reducing over ranges.slice(0, i) and indexing weights[j] directly.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Suggested reviewers

  • hardyjosh
🚥 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 directly describes the main change: handling a negative amountOut error, which is the core purpose of this bug fix PR across multiple files.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
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.

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

✨ 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 2026-06-23-handle-negative-amount-out-error

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

ESLint install timed out. The project may have too many dependencies for the sandbox.


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.

@coderabbitai coderabbitai Bot left a comment

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.

Actionable comments posted: 1

Caution

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

⚠️ Outside diff range comments (1)
src/router/sushi/index.ts (1)

284-295: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Clear signalReset before re-initialization to prevent sticky flag on failure.

If RainDataFetcher.init() throws an exception (lines 286-290), execution jumps to the empty catch block at line 293, and signalReset is never cleared. This leaves the flag permanently true, causing the CLI to attempt a reset every round.

Move the flag reset before the risky re-initialization so it's always cleared when a reset is attempted.

🔧 Proposed fix to clear flag before re-initialization
 async reset(): Promise<boolean> {
     try {
+        this.signalReset = false;
         this.dataFetcher = await RainDataFetcher.init(
             this.chainId as ChainId,
             this.client as any,
             this.liquidityProviders,
         );
-        this.signalReset = false;
         return true;
     } catch {}
     return false;
 }
🤖 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/router/sushi/index.ts` around lines 284 - 295, The signalReset flag is
set to false after the RainDataFetcher.init() call in the reset() method, but if
that initialization throws an exception, the flag is never cleared due to the
empty catch block, leaving it permanently true and causing repeated reset
attempts. Move the line that sets signalReset to false to execute before the try
block containing RainDataFetcher.init(), ensuring the flag is always cleared
when a reset is attempted regardless of whether the initialization succeeds or
fails.
🤖 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/router/sushi/index.ts`:
- Line 104: The signalReset property is currently public, which could allow
external code to modify internal router state. Rename the signalReset property
to _signalReset to make it private, then create a public getter method that
returns its value. Update all internal references to signalReset to use the
private _signalReset property instead, including the assignments and reads that
occur throughout the router implementation.

---

Outside diff comments:
In `@src/router/sushi/index.ts`:
- Around line 284-295: The signalReset flag is set to false after the
RainDataFetcher.init() call in the reset() method, but if that initialization
throws an exception, the flag is never cleared due to the empty catch block,
leaving it permanently true and causing repeated reset attempts. Move the line
that sets signalReset to false to execute before the try block containing
RainDataFetcher.init(), ensuring the flag is always cleared when a reset is
attempted regardless of whether the initialization succeeds or fails.
🪄 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: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 4244b5e3-139e-49fe-b6af-3186eaaaf96f

📥 Commits

Reviewing files that changed from the base of the PR and between 14199b5 and 80dddc0.

📒 Files selected for processing (4)
  • src/cli/index.ts
  • src/router/sushi/error.ts
  • src/router/sushi/index.ts
  • src/rpc/helpers.ts

Comment thread src/router/sushi/index.ts
@rouzwelt rouzwelt merged commit b80c903 into master Jun 27, 2026
19 of 20 checks passed
@github-actions

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

coderabbitai Bot commented Jun 27, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

repo="rainlanguage/rain.solver"
pr="452"

echo "== PR metadata =="
gh pr view "$pr" --repo "$repo" --json number,title,baseRefName,headRefName,additions,deletions,changedFiles,labels,body

echo
echo "== Changed files =="
gh pr diff "$pr" --repo "$repo" --name-only

echo
echo "== Diff stat =="
gh pr diff "$pr" --repo "$repo" --stat

echo
echo "== Unified diff =="
gh pr diff "$pr" --repo "$repo" --patch

Length of output: 3046



SIZE=M

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant