-
Notifications
You must be signed in to change notification settings - Fork 618
SDK, Dashboard: Fix SwapWidget setting same token for buy and sell in chain page #8067
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
SDK, Dashboard: Fix SwapWidget setting same token for buy and sell in chain page #8067
Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
🦋 Changeset detectedLatest commit: 4796871 The changes in this PR will be included in the next version bump. This PR includes changesets to release 3 packages
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 |
WalkthroughAdds 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
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₀ }
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Pre-merge checks and finishing touches❌ Failed checks (2 warnings)
✅ Passed checks (1 passed)
✨ Finishing touches
🧪 Generate unit tests
Warning Review ran into problems🔥 ProblemsErrors were encountered while retrieving linked issues. Errors (1)
Comment |
How to use the Graphite Merge QueueAdd either label to this PR to merge it via the merge queue:
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. |
size-limit report 📦
|
There was a problem hiding this 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
getAddressfor 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.buyTokenandprefill.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: ExposeclassNameon 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.
📒 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@/typesor localtypes.tsbarrels
Prefer type aliases over interface except for nominal shapes
Avoidanyandunknownunless 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@/typeswhere applicable
Prefertypealiases overinterfaceexcept for nominal shapes
Avoidanyandunknownunless 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.tsxapps/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.tsxapps/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@exampleand 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
UseNavLinkfor internal navigation with automatic active states in dashboard and playground apps
Use Tailwind CSS only – no inline styles or CSS modules
Usecn()from@/lib/utilsfor conditional class logic
Use design system tokens (e.g.,bg-card,border-border,text-muted-foreground)
Server Components (Node edge): Start files withimport "server-only";
Client Components (browser): Begin files with'use client';
Always callgetAuthToken()to retrieve JWT from cookies on server side
UseAuthorization: Bearerheader – never embed tokens in URLs
Return typed results (e.g.,Project[],User[]) – avoidany
Wrap client-side data fetching calls in React Query (@tanstack/react-query)
Use descriptive, stablequeryKeysfor React Query cache hits
ConfigurestaleTime/cacheTimein React Query based on freshness (default ≥ 60s)
Keep tokens secret via internal API routes or server actions
Never importposthog-jsin 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)
UseNavLinkfor internal navigation to get active state handling
Use Tailwind CSS for styling; no inline styles
Merge class names withcn()from@/lib/utilsfor conditional classes
Stick to design tokens (e.g., bg-card, border-border, text-muted-foreground)
Server Components must start withimport "server-only"; usenext/headers, server‑only env, heavy data fetching, andredirect()where appropriate
Client Components must start with'use client'; handle interactivity with hooks and browser APIs
Server-side data fetching: callgetAuthToken()from cookies, sendAuthorization: Bearer <token>header, and return typed results (avoidany)
Client-side data fetching: wrap calls in React Query with descriptive, stablequeryKeysand set sensiblestaleTime/cacheTime(≥ 60s default); keep tokens secret via internal routes or server actions
Do not importposthog-jsin server components (client-side only)
Files:
apps/dashboard/src/@/components/blocks/BuyAndSwapEmbed.tsx
apps/{dashboard,playground}/**/*.tsx
📄 CodeRabbit inference engine (AGENTS.md)
Expose a
classNameprop 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 inpackages/*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
thirdwebmatches 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
getInitialSellTokensimplifies control flow and aligns with the storage prefill.Please confirm
setLastUsedTokenstoleratesundefinedforbuyTokenwhen 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
buyTokento native only whensellTokenis ERC20 addresses the chain page issue.

PR-Codex overview
This PR focuses on fixing the
SwapWidgetcomponent to correctly handle scenarios where the same token is used for both buying and selling. It ensures that thebuyTokenis only set if it is not the same as thesellToken.Detailed summary
BuyAndSwapEmbed.tsxto conditionally setbuyToken.SwapWidget.tsxto prevent using the same token for both buy and sell.getInitialSellTokenfunction to streamline sell token initialization.Summary by CodeRabbit
Bug Fixes
Chores