Skip to content

Conversation

jjramirezn
Copy link
Contributor

Stop using the skd and use the squid API directly, this give us more control and access to all the data that returns squid (for example, we now have access to the fees and don't have to recalculate them ourselves)

Stop using the skd and use the squid API directly, this give us more
control and access to all the data that returns squid (for example,
we now have access to the fees and don't have to recalculate them
ourselves)
Copy link

vercel bot commented Jun 12, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
peanut-ui ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jun 13, 2025 3:38pm

Copy link

Copy link
Contributor

coderabbitai bot commented Jun 12, 2025

Caution

Review failed

The pull request is closed.

"""

Walkthrough

This update simplifies the token decimals extraction logic in the token actions module and adds a new service module that fetches and optimizes cross-chain token swap routes using the Squid API. The new service includes detailed TypeScript types, route fetching, binary search optimization for amounts, fee aggregation, and USD conversions. Additionally, the Squid API URL constant was changed to be sourced from an environment variable instead of a hardcoded string.

Changes

Files Change Summary
src/app/actions/tokens.ts Simplified decimals extraction by removing fallback to JSON data, directly using contract lookup.
src/services/swap.ts Added new module for cross-chain swap route fetching and optimization via Squid API with extensive types and logic.
src/constants/general.consts.ts Changed SQUID_API_URL constant to read from environment variable instead of hardcoded string.

Suggested reviewers

  • Hugo0
    """

📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f912a12 and 2ed2dd3.

📒 Files selected for processing (2)
  • src/constants/general.consts.ts (1 hunks)
  • src/services/swap.ts (1 hunks)
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate Unit Tests
  • Create PR with Unit Tests
  • Commit Unit Tests in branch feat/abstract-squid-route-fetching
  • Post Copyable Unit Tests in Comment

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 auto-generate unit tests to generate unit tests for 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.

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: 3

🔭 Outside diff range comments (1)
src/app/actions/tokens.ts (1)

78-88: ⚠️ Potential issue

Guard against missing contract match before non-null assertion

json.data.contracts.find(…)!.decimals will throw if blockchainId doesn’t exactly match chainId (Mobula sometimes uses numeric IDs or differing case).
Add a fallback or explicit error to avoid a runtime crash:

-const decimals = json.data.contracts.find((c) => c.blockchainId === chainId)!.decimals
+const contractMatch = json.data.contracts.find((c) => c.blockchainId === chainId)
+const decimals =
+    contractMatch?.decimals ??
+    json.data.decimals ??                 // legacy field
+    18                                    // sensible default
🧹 Nitpick comments (1)
src/services/swap.ts (1)

235-239: maxIterations = 3 risks missing an optimal amount

With only three iterations the binary search covers at most 8 values—often insufficient for tight tolerances, especially on wider ranges (e.g., USD mode). Consider increasing or making it configurable.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0818f95 and 3580ed5.

📒 Files selected for processing (2)
  • src/app/actions/tokens.ts (1 hunks)
  • src/services/swap.ts (1 hunks)

jjramirezn and others added 2 commits June 11, 2025 23:11
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
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

♻️ Duplicate comments (2)
src/services/swap.ts (2)

176-189: Remove unconditional logging & validate env vars (already flagged).

console.dir leaks wallet addresses / API secrets in prod logs, and ! does not guard at runtime against missing SQUID_API_URL / SQUID_INTEGRATOR_ID. Make the logs dev-only and throw early if the env vars are absent (see earlier review).


212-214: BigInt → Number cast drops precision (already flagged).

Number(formatUnits(..)) * price loses accuracy for large 18-dec tokens. Keep everything in big-number arithmetic instead of casting to JS numbers.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 3580ed5 and 91e1624.

📒 Files selected for processing (1)
  • src/services/swap.ts (1 hunks)
🧰 Additional context used
🧠 Learnings (1)
src/services/swap.ts (1)
Learnt from: jjramirezn
PR: peanutprotocol/peanut-ui#495
File: src/components/Cashout/Components/Initial.view.tsx:194-198
Timestamp: 2024-10-29T14:44:08.745Z
Learning: Using a fixed 6 decimal places for `floorFixed` is acceptable for token amounts in this codebase, even if tokens have varying decimal places.

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

♻️ Duplicate comments (4)
src/services/swap.ts (4)

210-211: Precision loss converting BigInt → Number
Number(formatUnits(...)) drops precision for 18-dec tokens above 2⁵³-1 and can mis-size the tolerance window. Same issue was flagged in previous PRs.
Use big-number arithmetic or a decimal lib instead.


245-247: overage calculation can overflow Number

Number(receivedAmount - targetToAmount) risks precision loss for large amounts; the comparison that follows then uses this inaccuracy to decide search bounds. Switch to bigint math or at least a safe-int check.


317-320: Possible scientific-notation string breaks parseUnits

(Number(amount.fromUsd) / fromTokenPrice.price).toString() can yield "1e-7", which parseUnits rejects. Format the number with toFixed(fromTokenPrice.decimals) as done later in the file.


176-183: ⚠️ Potential issue

Validate env vars before constructing the request URL & headers

process.env.SQUID_API_URL! and process.env.SQUID_INTEGRATOR_ID! are asserted non-null, yet no explicit guard exists.
If either is undefined the code silently builds a URL like "undefined/v2/route" or sends an empty integrator id – easy to overlook in prod and hard to diagnose.

-    const response = await fetchWithSentry(`${process.env.SQUID_API_URL!}/v2/route`, {
-        method: 'POST',
-        headers: {
-            'Content-Type': 'application/json',
-            'x-integrator-id': process.env.SQUID_INTEGRATOR_ID!,
-        },
+    const apiUrl = process.env.SQUID_API_URL
+    const integratorId = process.env.SQUID_INTEGRATOR_ID
+    if (!apiUrl || !integratorId) {
+        throw new Error('SQUID_API_URL or SQUID_INTEGRATOR_ID env var not set')
+    }
+
+    const response = await fetchWithSentry(`${apiUrl}/v2/route`, {
+        method: 'POST',
+        headers: {
+            'Content-Type': 'application/json',
+            'x-integrator-id': integratorId,
+        },
🧹 Nitpick comments (2)
src/services/swap.ts (2)

236-244: Binary-search capped to 3 iterations may miss the tolerance window

With only three requests the search space is reduced by 8× at best; for widely spaced liquidity steps you could exit without ever probing a viable quote.
Consider:

  • Increasing maxIterations, or
  • Using an exponential probing phase before binary search, or
  • Accepting the first quote within maxOverage irrespective of iteration count.

372-375: Casting amountUsd strings to Number may silently truncate large values

Number(cost.amountUsd) assumes the value is < 2⁵³ and non-scientific notation. For consistency with other bigint-centric code, consider keeping these as strings and using a decimal library (e.g. decimal.js) for the sum.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 91e1624 and fa45a11.

📒 Files selected for processing (1)
  • src/services/swap.ts (1 hunks)
🧰 Additional context used
🧠 Learnings (1)
src/services/swap.ts (1)
Learnt from: jjramirezn
PR: peanutprotocol/peanut-ui#495
File: src/components/Cashout/Components/Initial.view.tsx:194-198
Timestamp: 2024-10-29T14:44:08.745Z
Learning: Using a fixed 6 decimal places for `floorFixed` is acceptable for token amounts in this codebase, even if tokens have varying decimal places.

Copy link
Contributor

@kushagrasarathe kushagrasarathe left a comment

Choose a reason for hiding this comment

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

@jjramirezn left some qns, and nits, rest lgtm LFG 🫡

@jjramirezn jjramirezn merged commit d53235d into feat/coral-integration Jun 13, 2025
3 of 4 checks passed
@jjramirezn jjramirezn deleted the feat/abstract-squid-route-fetching branch June 13, 2025 15:35
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