Skip to content

Conversation

@MananTank
Copy link
Member

@MananTank MananTank commented Sep 17, 2025


PR-Codex overview

This PR focuses on fixing the SwapWidget component to correctly handle scenarios where the same token is used for both buying and selling. It ensures that the buyToken is only set if it is not the same as the sellToken.

Detailed summary

  • Updated logic in BuyAndSwapEmbed.tsx to conditionally set buyToken.
  • Enhanced SwapWidget.tsx to prevent using the same token for both buy and sell.
  • Introduced getInitialSellToken function to streamline sell token initialization.

✨ Ask PR-Codex anything about this PR by commenting with /codex {your question}

Summary by CodeRabbit

  • Bug Fixes

    • SwapWidget no longer defaults buy and sell to the same token when restoring last-used selections.
    • Improved initial token selection logic to respect prefilled values and chain IDs.
    • Consistent handling of native tokens; buy token is not prefilled if it matches the sell token.
    • Dashboard embed updated to only prefill buy token when appropriate.
  • Chores

    • Added a changeset entry documenting the patch release and the SwapWidget fix.

@vercel
Copy link

vercel bot commented Sep 17, 2025

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Preview Comments Updated (UTC)
docs-v2 Ready Ready Preview Comment Sep 17, 2025 10:29pm
nebula Ready Ready Preview Comment Sep 17, 2025 10:29pm
thirdweb_playground Ready Ready Preview Comment Sep 17, 2025 10:29pm
thirdweb-www Ready Ready Preview Comment Sep 17, 2025 10:29pm
wallet-ui Ready Ready Preview Comment Sep 17, 2025 10:29pm

@changeset-bot
Copy link

changeset-bot bot commented Sep 17, 2025

🦋 Changeset detected

Latest commit: 4796871

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 3 packages
Name Type
thirdweb Patch
@thirdweb-dev/nebula Patch
@thirdweb-dev/wagmi-adapter Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Sep 17, 2025

Walkthrough

Adds a changeset note for a patch about SwapWidget initialization. Updates BuyAndSwapEmbed prefill logic for buyToken. Refactors SwapWidget initialization to unify sellToken derivation and prevent buyToken from duplicating sellToken when loading last-used tokens.

Changes

Cohort / File(s) Summary
Release notes
\.changeset/cuddly-steaks-bathe.md
Adds patch changeset documenting a fix to prevent buy/sell tokens from being identical when restored from storage. No code changes.
Dashboard embed prefill
apps/dashboard/src/@/components/blocks/BuyAndSwapEmbed.tsx
Makes SwapWidget.prefill.buyToken conditional: sets buyToken only when a tokenAddress exists; otherwise undefined. Adds comment clarifying native token usage when sellToken is not native.
Swap widget initialization logic
packages/thirdweb/src/react/web/ui/Bridge/swap-widget/SwapWidget.tsx
Introduces getInitialSellToken(prefill, lastUsedSellToken). Refactors initial sellToken to use helper. Adjusts initial buyToken: uses lastUsedBuyToken unless it matches the computed sellToken (same chainId and address, case-insensitive), in which case buyToken is undefined. No API surface changes.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant U as Consumer
  participant W as SwapWidget
  participant S as Storage (last-used tokens)

  U->>W: Instantiate SwapWidget(props.prefill)
  W->>S: getLastUsedTokens()
  S-->>W: { buyToken?, sellToken? }

  rect rgba(200,230,255,0.25)
    note over W: Compute initial sell token
    W->>W: getInitialSellToken(prefill.sellToken, lastUsed.sellToken)
    W-->>W: sellToken₀
  end

  rect rgba(200,255,200,0.25)
    note over W: Compute initial buy token
    W->>W: lastUsedBuyToken := lastUsed.buyToken
    alt lastUsedBuyToken matches sellToken₀ (same chainId & address)
      W->>W: buyToken₀ := undefined
    else
      W->>W: buyToken₀ := lastUsedBuyToken
    end
  end

  W-->>U: Initialized state { sellToken: sellToken₀, buyToken: buyToken₀ }
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Pre-merge checks and finishing touches

❌ Failed checks (2 warnings)
Check name Status Explanation Resolution
Description Check ⚠️ Warning The PR description contains a PR-Codex overview that summarizes the change, but the repository's required template sections are left as commented placeholders: "Notes for the reviewer" and "How to test" are not populated with concrete guidance or test steps, so essential reviewer and QA information is missing. Please populate the required template fields: add the PR title in the requested format, fill "Notes for the reviewer" with rationale and any non-obvious implementation details, and provide explicit "How to test" instructions (unit commands, manual QA steps, and expected results); also link any related issue/Linear ID and include Graphite merge-queue instructions separately if applicable.
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (1 passed)
Check name Status Explanation
Title Check ✅ Passed The title succinctly captures the primary change—fixing SwapWidget so it does not set the same token for buy and sell—and correctly references the affected areas (SDK, Dashboard), which aligns with the changes in SwapWidget.tsx and BuyAndSwapEmbed.tsx.
✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch 09-18-sdk_dashboard_fix_swapwidget_setting_same_token_for_buy_and_sell_in_chain_page

Warning

Review ran into problems

🔥 Problems

Errors were encountered while retrieving linked issues.

Errors (1)
  • TEAM-0000: Entity not found: Issue - Could not find referenced Issue.

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

@github-actions github-actions bot added Dashboard Involves changes to the Dashboard. packages SDK Involves changes to the thirdweb SDK labels Sep 17, 2025
@MananTank MananTank marked this pull request as ready for review September 17, 2025 21:06
Copy link
Member Author


How to use the Graphite Merge Queue

Add either label to this PR to merge it via the merge queue:

  • merge-queue - adds this PR to the back of the merge queue
  • hotfix - for urgent hot fixes, skip the queue and merge this PR next

You must have a Graphite account in order to use the merge queue. Sign up using this link.

An organization admin has enabled the Graphite Merge Queue in this repository.

Please do not merge from GitHub as this will restart CI on PRs being processed by the merge queue.

This stack of pull requests is managed by Graphite. Learn more about stacking.

@MananTank MananTank requested review from a team as code owners September 17, 2025 21:06
@github-actions
Copy link
Contributor

size-limit report 📦

Path Size Loading time (3g) Running time (snapdragon) Total time
thirdweb (esm) 63.96 KB (0%) 1.3 s (0%) 277 ms (+249.27% 🔺) 1.6 s
thirdweb (cjs) 361.44 KB (0%) 7.3 s (0%) 905 ms (+22.86% 🔺) 8.2 s
thirdweb (minimal + tree-shaking) 5.73 KB (0%) 115 ms (0%) 106 ms (+2453.27% 🔺) 221 ms
thirdweb/chains (tree-shaking) 526 B (0%) 11 ms (0%) 57 ms (+2640.39% 🔺) 68 ms
thirdweb/react (minimal + tree-shaking) 19.15 KB (0%) 383 ms (0%) 87 ms (+1788.7% 🔺) 470 ms

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

🧹 Nitpick comments (4)
packages/thirdweb/src/react/web/ui/Bridge/swap-widget/SwapWidget.tsx (3)

326-346: Cache last-used tokens once and compare checksummed addresses.

Avoid multiple JSON parses and lowercase comparisons. Use getAddress for normalization.

-    const lastUsedBuyToken = getLastUsedTokens()?.buyToken;
+    const lastUsed = getLastUsedTokens();
+    const lastUsedBuyToken = lastUsed?.buyToken;

-    const sellToken = getInitialSellToken(
-      props.prefill,
-      getLastUsedTokens()?.sellToken,
-    );
+    const sellToken = getInitialSellToken(props.prefill, lastUsed?.sellToken);

-    if (
+    if (
       lastUsedBuyToken &&
       sellToken &&
-      lastUsedBuyToken.tokenAddress.toLowerCase() ===
-        sellToken.tokenAddress.toLowerCase() &&
+      getAddress(lastUsedBuyToken.tokenAddress) ===
+        getAddress(sellToken.tokenAddress) &&
       lastUsedBuyToken.chainId === sellToken.chainId
     ) {
       return undefined;
     }

326-346: Guard also when prefill sets identical buy/sell.

Current dedupe only applies for last‑used tokens. If a caller provides equal prefill.buyToken and prefill.sellToken, the early return on Line 318 will still set duplicates.

If you want to prevent this universally, add a prefill guard before the early return (outside this hunk). Example (for context, not in this hunk):

-  if (props.prefill?.buyToken) {
-    return {
-      tokenAddress:
-        props.prefill.buyToken.tokenAddress || getAddress(NATIVE_TOKEN_ADDRESS),
-      chainId: props.prefill.buyToken.chainId,
-    };
-  }
+  if (props.prefill?.buyToken) {
+    const computedSell = getInitialSellToken(props.prefill, getLastUsedTokens()?.sellToken);
+    const computedBuy = {
+      tokenAddress: props.prefill.buyToken.tokenAddress || getAddress(NATIVE_TOKEN_ADDRESS),
+      chainId: props.prefill.buyToken.chainId,
+    } as const;
+    if (
+      computedSell &&
+      computedSell.chainId === computedBuy.chainId &&
+      getAddress(computedSell.tokenAddress) === getAddress(computedBuy.tokenAddress)
+    ) {
+      return undefined; // avoid duplicate selection
+    }
+    return computedBuy;
+  }

515-528: Add an explicit return type.

Align with TS guidelines for explicit return types.

-function getInitialSellToken(
+function getInitialSellToken(
   prefill: SwapWidgetProps["prefill"],
   lastUsedSellToken: TokenSelection | undefined,
-) {
+): TokenSelection | undefined {
apps/dashboard/src/@/components/blocks/BuyAndSwapEmbed.tsx (1)

100-106: Expose className on the root container (project guideline).

This component doesn’t accept className; consider adding it to comply with app guidelines.

Example (outside this hunk):

-export function BuyAndSwapEmbed(props: {
-  client: ThirdwebClient;
-  chain: Chain;
-  tokenAddress: string | undefined;
-  buyAmount: string | undefined;
-  pageType: "asset" | "bridge" | "chain";
-}) {
+export function BuyAndSwapEmbed(props: {
+  client: ThirdwebClient;
+  chain: Chain;
+  tokenAddress: string | undefined;
+  buyAmount: string | undefined;
+  pageType: "asset" | "bridge" | "chain";
+  className?: string;
+}) {
   const { theme } = useTheme();
   const [tab, setTab] = useState<"buy" | "swap">("swap");
   const themeObj = getSDKTheme(theme === "light" ? "light" : "dark");
   return (
-    <div className="bg-card rounded-2xl border overflow-hidden flex flex-col">
+    <div className={cn("bg-card rounded-2xl border overflow-hidden flex flex-col", props.className)}>
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between a6f846f and 4796871.

📒 Files selected for processing (3)
  • .changeset/cuddly-steaks-bathe.md (1 hunks)
  • apps/dashboard/src/@/components/blocks/BuyAndSwapEmbed.tsx (1 hunks)
  • packages/thirdweb/src/react/web/ui/Bridge/swap-widget/SwapWidget.tsx (2 hunks)
🧰 Additional context used
📓 Path-based instructions (7)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (CLAUDE.md)

**/*.{ts,tsx}: Write idiomatic TypeScript with explicit function declarations and return types
Limit each file to one stateless, single-responsibility function for clarity
Re-use shared types from @/types or local types.ts barrels
Prefer type aliases over interface except for nominal shapes
Avoid any and unknown unless unavoidable; narrow generics when possible
Choose composition over inheritance; leverage utility types (Partial, Pick, etc.)
Comment only ambiguous logic; avoid restating TypeScript in prose

**/*.{ts,tsx}: Use explicit function declarations and explicit return types in TypeScript
Limit each file to one stateless, single‑responsibility function
Re‑use shared types from @/types where applicable
Prefer type aliases over interface except for nominal shapes
Avoid any and unknown unless unavoidable; narrow generics when possible
Prefer composition over inheritance; use utility types (Partial, Pick, etc.)
Lazy‑import optional features and avoid top‑level side‑effects to reduce bundle size

Files:

  • packages/thirdweb/src/react/web/ui/Bridge/swap-widget/SwapWidget.tsx
  • apps/dashboard/src/@/components/blocks/BuyAndSwapEmbed.tsx
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (CLAUDE.md)

Load heavy dependencies inside async paths to keep initial bundle lean (lazy loading)

Files:

  • packages/thirdweb/src/react/web/ui/Bridge/swap-widget/SwapWidget.tsx
  • apps/dashboard/src/@/components/blocks/BuyAndSwapEmbed.tsx
packages/thirdweb/**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

packages/thirdweb/**/*.{ts,tsx}: Every public symbol must have comprehensive TSDoc with at least one compiling @example and a custom tag (@beta, @internal, @experimental, etc.)
Comment only ambiguous logic; avoid restating TypeScript in prose
Lazy‑load heavy dependencies inside async paths (e.g., const { jsPDF } = await import("jspdf"))

Files:

  • packages/thirdweb/src/react/web/ui/Bridge/swap-widget/SwapWidget.tsx
apps/{dashboard,playground-web}/**/*.{ts,tsx}

📄 CodeRabbit inference engine (CLAUDE.md)

apps/{dashboard,playground-web}/**/*.{ts,tsx}: Import UI primitives from @/components/ui/* (Button, Input, Select, Tabs, Card, Sidebar, Badge, Separator) in dashboard and playground apps
Use NavLink for internal navigation with automatic active states in dashboard and playground apps
Use Tailwind CSS only – no inline styles or CSS modules
Use cn() from @/lib/utils for conditional class logic
Use design system tokens (e.g., bg-card, border-border, text-muted-foreground)
Server Components (Node edge): Start files with import "server-only";
Client Components (browser): Begin files with 'use client';
Always call getAuthToken() to retrieve JWT from cookies on server side
Use Authorization: Bearer header – never embed tokens in URLs
Return typed results (e.g., Project[], User[]) – avoid any
Wrap client-side data fetching calls in React Query (@tanstack/react-query)
Use descriptive, stable queryKeys for React Query cache hits
Configure staleTime/cacheTime in React Query based on freshness (default ≥ 60s)
Keep tokens secret via internal API routes or server actions
Never import posthog-js in server components

Files:

  • apps/dashboard/src/@/components/blocks/BuyAndSwapEmbed.tsx
apps/{dashboard,playground}/**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

apps/{dashboard,playground}/**/*.{ts,tsx}: Import UI primitives from @/components/ui/_ (e.g., Button, Input, Tabs, Card)
Use NavLink for internal navigation to get active state handling
Use Tailwind CSS for styling; no inline styles
Merge class names with cn() from @/lib/utils for conditional classes
Stick to design tokens (e.g., bg-card, border-border, text-muted-foreground)
Server Components must start with import "server-only"; use next/headers, server‑only env, heavy data fetching, and redirect() where appropriate
Client Components must start with 'use client'; handle interactivity with hooks and browser APIs
Server-side data fetching: call getAuthToken() from cookies, send Authorization: Bearer <token> header, and return typed results (avoid any)
Client-side data fetching: wrap calls in React Query with descriptive, stable queryKeys and set sensible staleTime/cacheTime (≥ 60s default); keep tokens secret via internal routes or server actions
Do not import posthog-js in server components (client-side only)

Files:

  • apps/dashboard/src/@/components/blocks/BuyAndSwapEmbed.tsx
apps/{dashboard,playground}/**/*.tsx

📄 CodeRabbit inference engine (AGENTS.md)

Expose a className prop on the root element of every component

Files:

  • apps/dashboard/src/@/components/blocks/BuyAndSwapEmbed.tsx
.changeset/*.md

📄 CodeRabbit inference engine (AGENTS.md)

.changeset/*.md: Each change in packages/* must include a changeset for the appropriate package
Version bump rules: patch for non‑API changes; minor for new/modified public API

Files:

  • .changeset/cuddly-steaks-bathe.md
🧬 Code graph analysis (1)
packages/thirdweb/src/react/web/ui/Bridge/swap-widget/SwapWidget.tsx (2)
packages/thirdweb/src/react/web/ui/Bridge/swap-widget/storage.ts (1)
  • getLastUsedTokens (23-41)
packages/thirdweb/src/react/web/ui/Bridge/swap-widget/types.ts (1)
  • TokenSelection (149-152)
⏰ 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). (5)
  • GitHub Check: E2E Tests (pnpm, vite)
  • GitHub Check: Unit Tests
  • GitHub Check: Size
  • GitHub Check: Lint Packages
  • GitHub Check: Analyze (javascript)
🔇 Additional comments (3)
.changeset/cuddly-steaks-bathe.md (1)

1-6: Changeset scope and bump look correct.

Patch bump for thirdweb matches a bug‑fix with no public API change. Good.

packages/thirdweb/src/react/web/ui/Bridge/swap-widget/SwapWidget.tsx (1)

349-350: LGTM: unified sell-token derivation.

Using getInitialSellToken simplifies control flow and aligns with the storage prefill.

Please confirm setLastUsedTokens tolerates undefined for buyToken when dedupe triggers (no schema violations or overwrites).

apps/dashboard/src/@/components/blocks/BuyAndSwapEmbed.tsx (1)

100-106: Good preventative prefill: avoids duplicate tokens.

Conditionally setting buyToken to native only when sellToken is ERC20 addresses the chain page issue.

@joaquim-verges joaquim-verges merged commit e0738d6 into main Sep 17, 2025
30 of 32 checks passed
@joaquim-verges joaquim-verges deleted the 09-18-sdk_dashboard_fix_swapwidget_setting_same_token_for_buy_and_sell_in_chain_page branch September 17, 2025 22:47
@joaquim-verges joaquim-verges mentioned this pull request Sep 17, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Dashboard Involves changes to the Dashboard. packages SDK Involves changes to the thirdweb SDK

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants