Skip to content

Comments

Fix/the exchange bugs#384

Merged
IAmKio merged 5 commits intostagingfrom
fix/the-exchange-bugs
Aug 8, 2025
Merged

Fix/the exchange bugs#384
IAmKio merged 5 commits intostagingfrom
fix/the-exchange-bugs

Conversation

@IAmKio
Copy link
Collaborator

@IAmKio IAmKio commented Aug 8, 2025

How Has This Been Tested?

  • Locally

Screenshots (if appropriate):

Types of changes

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to change)

Summary by CodeRabbit

  • Bug Fixes

    • Improved validation and error handling during the exchange process, including checks for required fields and enhanced error messages.
    • Enhanced robustness in decoding ERC20 transfer data, with clearer warnings for decoding failures.
    • Consistent handling of missing or invalid swap offers.
    • Added validation for transaction addresses and token data to prevent processing errors.
  • Refactor

    • Streamlined initialization of the SDK configuration to prevent repeated setup and added comprehensive error logging.
    • Improved code readability and maintainability with updated comments and variable handling.
    • Enhanced logging and error handling during chain switching and transaction preparation.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 8, 2025

Walkthrough

The changes introduce enhanced validation, error handling, and logging in the exchange flow. Key updates include stricter checks and error messages in the exchange action, improved error handling and initialization logic in the main app, more robust decoding in blockchain utilities, and clarified comments in wrapped token utilities. No public API signatures were altered.

Changes

Cohort / File(s) Change Summary
Exchange Action Validation & Transaction Handling
src/apps/the-exchange/components/ExchangeAction/ExchangeAction.tsx
Added validation for token selection and swap amount before proceeding; improved error messages and logging; removed unnecessary transaction finalization calls; enhanced transaction iteration with validation and safer value handling.
Offer Selection Logic
src/apps/the-exchange/hooks/useOffer.tsx
Refactored getBestOffer to use local variables, consistently return undefined for missing offers, and eliminated placeholder empty object returns; added comprehensive input validations and error throwing in transaction preparation.
App Initialization & Error Handling
src/apps/the-exchange/index.tsx
Moved LiFi SDK config initialization into a guarded useEffect; added useRef to prevent repeated setup; improved error handling and logging for config initialization and chain switching operations.
Blockchain Utility Decoding
src/apps/the-exchange/utils/blockchain.ts
Enhanced ERC20 transfer argument checks for robustness; added warning logging for decode failures.
Wrapped Token Utility Comments
src/apps/the-exchange/utils/wrappedTokens.ts
Clarified fallback behavior in comments regarding wrapped token address resolution; logic unchanged.

Sequence Diagram(s)

sequenceDiagram
  participant User
  participant ExchangeAction
  participant OfferHook
  participant BlockchainUtils
  participant AppInit

  User->>ExchangeAction: Click Exchange
  ExchangeAction->>ExchangeAction: Validate swapToken, receiveToken, amountSwap
  alt Validation fails
    ExchangeAction->>User: Show error message
    ExchangeAction-->>ExchangeAction: Abort
  else Validation passes
    ExchangeAction->>OfferHook: getBestOffer()
    OfferHook-->>ExchangeAction: Return best offer or undefined
    ExchangeAction->>BlockchainUtils: Decode transaction data
    BlockchainUtils-->>ExchangeAction: Return decoded value or warning
    ExchangeAction->>ExchangeAction: Prepare and send transactions
  end

  AppInit->>AppInit: On provider/wallet change
  AppInit->>AppInit: Initialize config (once)
  AppInit->>AppInit: Handle errors and log
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~15-25 minutes

Possibly related PRs

Poem

A bunny pressed "Exchange" with glee,
But tokens must be set, you see!
With checks and logs, the flow is tight,
Errors caught before they bite.
Wrapped tokens clear, the chains aligned—
This code’s as safe as bunny’s mind!
🐇✨

Note

🔌 MCP (Model Context Protocol) integration is now available in Early Access!

Pro users can now connect to remote MCP servers under the Integrations page to get reviews and chat conversations that understand additional development context.


📜 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 e77c128 and 0bcb9e9.

📒 Files selected for processing (1)
  • src/apps/the-exchange/hooks/useOffer.tsx (18 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/apps/the-exchange/hooks/useOffer.tsx
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: lint
  • GitHub Check: unit-tests
  • GitHub Check: build
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/the-exchange-bugs

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.
  • 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.

Support

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

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 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.

@github-actions github-actions bot temporarily deployed to Preview (fix/the-exchange-bugs) August 8, 2025 09:04 Inactive
@IAmKio IAmKio requested a review from vignesha22 August 8, 2025 09:04
@IAmKio IAmKio self-assigned this Aug 8, 2025
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

🧹 Nitpick comments (4)
src/apps/the-exchange/utils/blockchain.ts (2)

80-86: Safer decode guard — consider also verifying function name

Good hardening with array checks and bigint type guard. One small enhancement: also assert that decoded.functionName === 'transfer' to avoid relying solely on the method selector, which is robust here but belt-and-suspenders helps with future ABI changes.


89-89: Enrich warning context for observability

Include basic tx/swap context (e.g., swapToken.symbol, decimals) in the warning to aid debugging without logging sensitive data.

src/apps/the-exchange/hooks/useOffer.tsx (2)

211-213: Consistently return undefined on no routes/errors; consider unified error logging

The switch to undefined is consistent and avoids placeholder objects. Consider logging via your sentry helpers for errors (parallel to the rest of the app) to keep telemetry uniform.

Also applies to: 218-220


176-182: Avoid float math when applying 1% fee (precision)
The computation Number(fromAmount) * 0.99 can introduce rounding issues for tokens with many decimals. Prefer doing the 1% deduction in integer units.

Example outside this hunk:

// Precise computation in wei:
const fromAmountWei = parseUnits(String(fromAmount), fromTokenDecimals);
const fromAmountFeeDeductedWei = (fromAmountWei * 99n) / 100n;

const routesRequest: RoutesRequest = {
  // ...
  fromAmount: fromAmountFeeDeductedWei.toString(),
  // ...
};
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0e68b5c and 3882bf0.

📒 Files selected for processing (5)
  • src/apps/the-exchange/components/ExchangeAction/ExchangeAction.tsx (7 hunks)
  • src/apps/the-exchange/hooks/useOffer.tsx (1 hunks)
  • src/apps/the-exchange/index.tsx (3 hunks)
  • src/apps/the-exchange/utils/blockchain.ts (1 hunks)
  • src/apps/the-exchange/utils/wrappedTokens.ts (1 hunks)
🧰 Additional context used
🧠 Learnings (5)
📓 Common learnings
Learnt from: RanaBug
PR: pillarwallet/x#320
File: src/components/BottomMenuModal/HistoryModal/TransactionInfo.tsx:177-182
Timestamp: 2025-05-28T14:30:02.702Z
Learning: In the transaction history tracking feature, chain ID validation is performed earlier in the flow before the values reach the TransactionInfo component, so additional validation at the display level is not needed.
Learnt from: RanaBug
PR: pillarwallet/x#275
File: src/apps/the-exchange/components/DropdownTokensList/DropdownTokenList.tsx:180-195
Timestamp: 2025-03-28T09:22:22.712Z
Learning: In the Exchange app, `swapTokenList` and `receiveTokenList` are derived from `searchTokenResult` when search is active, so including `searchToken` in the useEffect dependency array that uses these lists would be redundant as the lists will update when search results change.
📚 Learning: 2025-05-23T14:44:33.911Z
Learnt from: RanaBug
PR: pillarwallet/x#315
File: src/apps/the-exchange/utils/wrappedTokens.ts:6-20
Timestamp: 2025-05-23T14:44:33.911Z
Learning: XDAI (Gnosis Chain) is intentionally excluded from the WRAPPED_NATIVE_TOKEN_ADDRESSES mapping in the exchange app's wrappedTokens utility.

Applied to files:

  • src/apps/the-exchange/utils/wrappedTokens.ts
📚 Learning: 2025-03-28T09:22:22.712Z
Learnt from: RanaBug
PR: pillarwallet/x#275
File: src/apps/the-exchange/components/DropdownTokensList/DropdownTokenList.tsx:180-195
Timestamp: 2025-03-28T09:22:22.712Z
Learning: In the Exchange app, `swapTokenList` and `receiveTokenList` are derived from `searchTokenResult` when search is active, so including `searchToken` in the useEffect dependency array that uses these lists would be redundant as the lists will update when search results change.

Applied to files:

  • src/apps/the-exchange/utils/wrappedTokens.ts
  • src/apps/the-exchange/components/ExchangeAction/ExchangeAction.tsx
  • src/apps/the-exchange/hooks/useOffer.tsx
  • src/apps/the-exchange/index.tsx
📚 Learning: 2025-06-17T09:20:44.533Z
Learnt from: RanaBug
PR: pillarwallet/x#334
File: src/apps/leaderboard/utils/index.tsx:91-94
Timestamp: 2025-06-17T09:20:44.533Z
Learning: In src/apps/leaderboard/utils/index.tsx, the getLastWeekMigrationData function intentionally uses currentWeek (not lastWeek) for the completedSwapWeek lookup. This is correct business logic - when retrieving last week's migration data, the function should check swap completion against the current week while using lastWeek for points and USD calculations.

Applied to files:

  • src/apps/the-exchange/components/ExchangeAction/ExchangeAction.tsx
  • src/apps/the-exchange/hooks/useOffer.tsx
📚 Learning: 2025-05-28T14:30:02.702Z
Learnt from: RanaBug
PR: pillarwallet/x#320
File: src/components/BottomMenuModal/HistoryModal/TransactionInfo.tsx:177-182
Timestamp: 2025-05-28T14:30:02.702Z
Learning: In the transaction history tracking feature, chain ID validation is performed earlier in the flow before the values reach the TransactionInfo component, so additional validation at the display level is not needed.

Applied to files:

  • src/apps/the-exchange/components/ExchangeAction/ExchangeAction.tsx
🧬 Code Graph Analysis (1)
src/apps/the-exchange/hooks/useOffer.tsx (2)
src/apps/the-exchange/utils/types.tsx (1)
  • SwapOffer (23-26)
src/apps/the-exchange/utils/blockchain.ts (1)
  • processEth (18-24)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: lint
  • GitHub Check: unit-tests
🔇 Additional comments (8)
src/apps/the-exchange/utils/wrappedTokens.ts (1)

39-41: Comment clarity LGTM; matches intentional XDAI exclusion

The generalized fallback comment is accurate and aligns with the prior decision to intentionally exclude XDAI from WRAPPED_NATIVE_TOKEN_ADDRESSES.

src/apps/the-exchange/hooks/useOffer.tsx (2)

203-209: Return a concrete SwapOffer or undefined (good)

Removal of the outer-scoped placeholder and returning a typed SwapOffer improves correctness and readability.


157-167: All consumers handle undefined safely
The only usage of getBestOffer is wrapped in the local getOffer helper in EnterAmount.tsx, which:

  • Catches thrown errors and returns an empty object fallback
  • Guards with if (offer && Object.keys(offer).length) before dereferencing
  • Skips dispatch in the debounced caller when offer is undefined

No further changes are needed.

src/apps/the-exchange/components/ExchangeAction/ExchangeAction.tsx (4)

125-137: Pre-flight token selection validation (good)

Early return with telemetry keeps the flow safe and user-friendly.


138-147: Amount validation added (good)

Prevents zero/negative swaps from entering the flow.


206-216: Null/empty step transactions guard (good)

The additional null check avoids crashes when LiFi yields no steps.


257-270: Safe optional chaining for calldata and logging (good)

Using ?.toString() ?? '' avoids undefined issues when building batch entries.

src/apps/the-exchange/index.tsx (1)

69-74: One-time config init — verify behavior on provider changes

The ref gate prevents re-init, which is good for stability. If the provider instance can change at runtime (wallet reconnect, account change with a new client), consider resetting the ref when the provider identity changes.

If relevant, track and compare the provider object:

const prevProvider = useRef<any>(null);
useEffect(() => {
  if (!provider) return;
  if (prevProvider.current && prevProvider.current !== provider) {
    configInitialized.current = false;
  }
  prevProvider.current = provider;
  // ... then run your guarded init
}, [provider, walletAddress]);

Also applies to: 152-153

@cloudflare-workers-and-pages
Copy link

cloudflare-workers-and-pages bot commented Aug 8, 2025

Deploying x with  Cloudflare Pages  Cloudflare Pages

Latest commit: 0bcb9e9
Status: ✅  Deploy successful!
Preview URL: https://9bda0d59.x-e62.pages.dev
Branch Preview URL: https://fix-the-exchange-bugs.x-e62.pages.dev

View logs

@github-actions github-actions bot temporarily deployed to Preview (fix/the-exchange-bugs) August 8, 2025 09:34 Inactive
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

🔭 Outside diff range comments (2)
src/apps/the-exchange/hooks/useOffer.tsx (2)

341-347: totalNativeRequired double-counts swap amount when wrapping

The intention is “swap amount + fee”, but the current formula adds the full amount twice (fromAmountBigInt and again fromAmountBigInt - feeAmount), so the balance check requires almost 2× the real need.

-totalNativeRequired = fromAmountBigInt;
-if (isWrapRequired) {
-  totalNativeRequired += fromAmountBigInt - feeAmount;
-}
+totalNativeRequired = fromAmountBigInt;          // swap amount
+if (isWrapRequired) {
+  totalNativeRequired = fromAmountBigInt;        // still just swap amount
+}
+totalNativeRequired += feeAmount;                // plus 1 % fee

519-524: Numeric comparison is lexicographic – convert to BigInt first

formatUnits returns strings; comparing them with >= compares string bytes, not numbers ('20' > '100'true).
Parse them back to BigInt (or use Big.js) before comparison.

-const isEnoughAllowance = isAllowance
-  ? formatUnits(isAllowance, step.action.fromToken.decimals) >=
-    formatUnits(BigInt(step.action.fromAmount), step.action.fromToken.decimals)
+const isEnoughAllowance = isAllowance
+  ? isAllowance >= BigInt(step.action.fromAmount)
   : undefined;
🧹 Nitpick comments (1)
src/apps/the-exchange/index.tsx (1)

252-253: Trim unnecessary dependency to prevent redundant effect runs

walletAddress is not used inside this effect.
Removing it avoids a (harmless) re-render path and keeps the dependency list minimal.

-}, [provider, walletAddress]);
+}, [provider]);
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 82557c5 and e77c128.

📒 Files selected for processing (3)
  • src/apps/the-exchange/components/ExchangeAction/ExchangeAction.tsx (7 hunks)
  • src/apps/the-exchange/hooks/useOffer.tsx (18 hunks)
  • src/apps/the-exchange/index.tsx (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/apps/the-exchange/components/ExchangeAction/ExchangeAction.tsx
🧰 Additional context used
🧠 Learnings (5)
📓 Common learnings
Learnt from: RanaBug
PR: pillarwallet/x#320
File: src/components/BottomMenuModal/HistoryModal/TransactionInfo.tsx:177-182
Timestamp: 2025-05-28T14:30:02.702Z
Learning: In the transaction history tracking feature, chain ID validation is performed earlier in the flow before the values reach the TransactionInfo component, so additional validation at the display level is not needed.
Learnt from: RanaBug
PR: pillarwallet/x#275
File: src/apps/the-exchange/components/DropdownTokensList/DropdownTokenList.tsx:180-195
Timestamp: 2025-03-28T09:22:22.712Z
Learning: In the Exchange app, `swapTokenList` and `receiveTokenList` are derived from `searchTokenResult` when search is active, so including `searchToken` in the useEffect dependency array that uses these lists would be redundant as the lists will update when search results change.
📚 Learning: 2025-03-28T09:22:22.712Z
Learnt from: RanaBug
PR: pillarwallet/x#275
File: src/apps/the-exchange/components/DropdownTokensList/DropdownTokenList.tsx:180-195
Timestamp: 2025-03-28T09:22:22.712Z
Learning: In the Exchange app, `swapTokenList` and `receiveTokenList` are derived from `searchTokenResult` when search is active, so including `searchToken` in the useEffect dependency array that uses these lists would be redundant as the lists will update when search results change.

Applied to files:

  • src/apps/the-exchange/hooks/useOffer.tsx
  • src/apps/the-exchange/index.tsx
📚 Learning: 2025-06-17T09:20:44.533Z
Learnt from: RanaBug
PR: pillarwallet/x#334
File: src/apps/leaderboard/utils/index.tsx:91-94
Timestamp: 2025-06-17T09:20:44.533Z
Learning: In src/apps/leaderboard/utils/index.tsx, the getLastWeekMigrationData function intentionally uses currentWeek (not lastWeek) for the completedSwapWeek lookup. This is correct business logic - when retrieving last week's migration data, the function should check swap completion against the current week while using lastWeek for points and USD calculations.

Applied to files:

  • src/apps/the-exchange/hooks/useOffer.tsx
📚 Learning: 2025-05-23T14:44:33.911Z
Learnt from: RanaBug
PR: pillarwallet/x#315
File: src/apps/the-exchange/utils/wrappedTokens.ts:6-20
Timestamp: 2025-05-23T14:44:33.911Z
Learning: XDAI (Gnosis Chain) is intentionally excluded from the WRAPPED_NATIVE_TOKEN_ADDRESSES mapping in the exchange app's wrappedTokens utility.

Applied to files:

  • src/apps/the-exchange/hooks/useOffer.tsx
📚 Learning: 2025-05-28T14:30:02.702Z
Learnt from: RanaBug
PR: pillarwallet/x#320
File: src/components/BottomMenuModal/HistoryModal/TransactionInfo.tsx:177-182
Timestamp: 2025-05-28T14:30:02.702Z
Learning: In the transaction history tracking feature, chain ID validation is performed earlier in the flow before the values reach the TransactionInfo component, so additional validation at the display level is not needed.

Applied to files:

  • src/apps/the-exchange/hooks/useOffer.tsx
  • src/apps/the-exchange/index.tsx
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: unit-tests
  • GitHub Check: lint
  • GitHub Check: build

Copy link
Contributor

@vignesha22 vignesha22 left a comment

Choose a reason for hiding this comment

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

LGTM

@IAmKio IAmKio merged commit ec8ff68 into staging Aug 8, 2025
6 checks passed
@IAmKio IAmKio deleted the fix/the-exchange-bugs branch August 8, 2025 10:26
@coderabbitai coderabbitai bot mentioned this pull request Aug 26, 2025
3 tasks
@coderabbitai coderabbitai bot mentioned this pull request Oct 24, 2025
3 tasks
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