-
Notifications
You must be signed in to change notification settings - Fork 636
[MNY-342] Dashboard: Add Buy Widget iframe #8613
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
Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
WalkthroughAdds a Buy Widget iframe at /bridge/buy-widget: CSP header routes, a new NEXT_PUBLIC_BUY_IFRAME_CLIENT_ID env binding, and new layout, page, and client embed components that render a ThirdWeb BuyWidget and relay success/error via postMessage to the parent window. Changes
Sequence Diagram(s)sequenceDiagram
participant Parent as Parent Window
participant Page as BuyWidget Page
participant Embed as BuyWidgetEmbed (iframe)
participant ThirdWeb as ThirdWeb BuyWidget
Parent->>Page: Navigate to /bridge/buy-widget?...
Page->>Embed: Render with parsed config props
Embed->>Embed: init ThirdWeb client (using NEXT_PUBLIC_BUY_IFRAME_CLIENT_ID)
Embed->>ThirdWeb: Render BuyWidget with props
ThirdWeb->>ThirdWeb: User interacts (purchase)
rect rgba(76,175,80,0.12)
Note over ThirdWeb,Embed: Success path
ThirdWeb->>Embed: onSuccess event
Embed->>Embed: sendMessageToParent(success payload)
Embed->>Parent: postMessage(success)
end
rect rgba(244,67,54,0.08)
Note over ThirdWeb,Embed: Error path
ThirdWeb->>Embed: onError event
Embed->>Embed: sendMessageToParent(error payload)
Embed->>Parent: postMessage(error)
end
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing touches
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. |
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #8613 +/- ##
=======================================
Coverage 53.05% 53.05%
=======================================
Files 924 924
Lines 61738 61738
Branches 4039 4039
=======================================
Hits 32757 32757
Misses 28884 28884
Partials 97 97
🚀 New features to boost your workflow:
|
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: 2
🤖 Fix all issues with AI agents
In @apps/dashboard/src/app/bridge/buy-widget/page.tsx:
- Around line 1-11: This file is a Next.js server component but is missing the
required module directive; add import "server-only"; as the very first statement
in the file (before any other imports) to prevent accidental client-side
bundling; ensure it precedes the existing imports such as Metadata,
isValidCurrency, parseQueryParams, BridgeProvidersLite and BuyWidgetEmbed so the
component is treated as server-only.
- Around line 65-70: The paymentMethods parsing in parseQueryParams currently
only accepts a single value and will drop comma-separated or multi-value inputs;
update the parser used for searchParams.paymentMethods so it splits the input on
commas (or handles array inputs), trims each entry, filters to the allowed set
("crypto" | "card"), and returns the array (even if length 1) so BuyWidgetEmbed
receives an array of methods; reference the parseQueryParams call for
paymentMethods and ensure the validator returns ("crypto" | "card")[] or
undefined when no valid methods remain.
🧹 Nitpick comments (1)
apps/dashboard/src/app/bridge/buy-widget/BuyWidgetEmbed.client.tsx (1)
9-86: Add explicit return type annotation.The coding guidelines recommend explicit return types for functions. Add
: React.JSX.Elementor: JSX.Elementto the function signature.♻️ Proposed fix
-export function BuyWidgetEmbed({ +export function BuyWidgetEmbed({ chainId, tokenAddress, // ... props -}) { +}): React.JSX.Element {Based on coding guidelines: "Write idiomatic TypeScript with explicit function declarations and return types"
📜 Review details
Configuration used: Organization 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 (5)
apps/dashboard/next.config.tsapps/dashboard/src/@/constants/public-envs.tsapps/dashboard/src/app/bridge/buy-widget/BuyWidgetEmbed.client.tsxapps/dashboard/src/app/bridge/buy-widget/layout.tsxapps/dashboard/src/app/bridge/buy-widget/page.tsx
🧰 Additional context used
📓 Path-based instructions (11)
**/*.{ts,tsx}
📄 CodeRabbit inference engine (CLAUDE.md)
**/*.{ts,tsx}: Write idiomatic TypeScript with explicit function declarations and return types
Limit each TypeScript 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 in TypeScript
Avoidanyandunknownin TypeScript unless unavoidable; narrow generics when possible
Choose composition over inheritance; leverage utility types (Partial,Pick, etc.) in TypeScript
**/*.{ts,tsx}: Write idiomatic TypeScript with explicit function declarations and return types
Limit each file to one stateless, single-responsibility function for clarity and testability
Re-use shared types from @/types or local types.ts barrel exports
Prefer type aliases over interface except for nominal shapes
Avoid any and unknown unless unavoidable; narrow generics whenever possible
Choose composition over inheritance; leverage utility types (Partial, Pick, etc.)
Comment only ambiguous logic in TypeScript files; avoid restating TypeScript types and signatures in prose
Files:
apps/dashboard/src/app/bridge/buy-widget/layout.tsxapps/dashboard/src/@/constants/public-envs.tsapps/dashboard/src/app/bridge/buy-widget/page.tsxapps/dashboard/next.config.tsapps/dashboard/src/app/bridge/buy-widget/BuyWidgetEmbed.client.tsx
apps/{dashboard,playground-web}/src/**/*.{ts,tsx}
📄 CodeRabbit inference engine (CLAUDE.md)
apps/{dashboard,playground-web}/src/**/*.{ts,tsx}: Import UI component primitives from@/components/ui/*(Button, Input, Select, Tabs, Card, Sidebar, Badge, Separator) in dashboard and playground
Use Tailwind CSS only – no inline styles or CSS modules in dashboard and playground
Usecn()from@/lib/utilsfor conditional Tailwind class merging
Use design system tokens for styling (backgrounds:bg-card, borders:border-border, muted text:text-muted-foreground)
ExposeclassNameprop on root element for component overrides
Files:
apps/dashboard/src/app/bridge/buy-widget/layout.tsxapps/dashboard/src/@/constants/public-envs.tsapps/dashboard/src/app/bridge/buy-widget/page.tsxapps/dashboard/src/app/bridge/buy-widget/BuyWidgetEmbed.client.tsx
apps/dashboard/src/**/*.{ts,tsx}
📄 CodeRabbit inference engine (CLAUDE.md)
apps/dashboard/src/**/*.{ts,tsx}: UseNavLinkfor internal navigation with automatic active states in dashboard
Start server component files withimport "server-only";in Next.js
Read cookies/headers withnext/headersin server components
Access server-only environment variables in server components
Perform heavy data fetching in server components
Implement redirect logic withredirect()fromnext/navigationin server components
Begin client component files with'use client';directive in Next.js
Handle interactive UI with React hooks (useState,useEffect, React Query, wallet hooks) in client components
Access browser APIs (localStorage,window,IntersectionObserver) in client components
Support fast transitions with prefetched data in client components
Always callgetAuthToken()to retrieve JWT from cookies on server side
UseAuthorization: Bearerheader for API calls – never embed tokens in URLs
Return typed results (Project[],User[]) from server-side data fetches – avoidany
Wrap client-side API calls in React Query (@tanstack/react-query)
Use descriptive, stablequeryKeysin React Query for 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 – only use analytics client-side
Files:
apps/dashboard/src/app/bridge/buy-widget/layout.tsxapps/dashboard/src/@/constants/public-envs.tsapps/dashboard/src/app/bridge/buy-widget/page.tsxapps/dashboard/src/app/bridge/buy-widget/BuyWidgetEmbed.client.tsx
apps/dashboard/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/dashboard.mdc)
apps/dashboard/**/*.{ts,tsx}: Always import from the central UI library under@/components/ui/*for reusable core UI components likeButton,Input,Select,Tabs,Card,Sidebar,Separator,Badge
UseNavLinkfrom@/components/ui/NavLinkfor internal navigation to ensure active states are handled automatically
For notices and skeletons, rely onAnnouncementBanner,GenericLoadingPage, andEmptyStateCardcomponents
Import icons fromlucide-reactor the project-specific…/iconsexports; never embed raw SVG
Keep components pure; fetch data outside using server components or hooks and pass it down via props
Use Tailwind CSS as the styling system; avoid inline styles or CSS modules
Merge class names withcnfrom@/lib/utilsto keep conditional logic readable
Stick to design tokens: usebg-card,border-border,text-muted-foregroundand other Tailwind variables instead of hard-coded colors
Use spacing utilities (px-*,py-*,gap-*) instead of custom margins
Follow mobile-first responsive design with Tailwind helpers (max-sm,md,lg,xl)
Never hard-code colors; always use Tailwind variables
Combine class names viacn, and exposeclassNameprop if useful in components
Use React Query (@tanstack/react-query) for all client-side data fetching with typed hooks
Files:
apps/dashboard/src/app/bridge/buy-widget/layout.tsxapps/dashboard/src/@/constants/public-envs.tsapps/dashboard/src/app/bridge/buy-widget/page.tsxapps/dashboard/next.config.tsapps/dashboard/src/app/bridge/buy-widget/BuyWidgetEmbed.client.tsx
apps/dashboard/**/layout.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/dashboard.mdc)
apps/dashboard/**/layout.{ts,tsx}: ReuseSidebarLayoutorFullWidthSidebarLayoutfrom@/components/blocks/SidebarLayoutfor all layouts
Export default async functions without'use client';in server components; they run on the Node edge
Files:
apps/dashboard/src/app/bridge/buy-widget/layout.tsx
**/*.{js,jsx,ts,tsx,json}
📄 CodeRabbit inference engine (AGENTS.md)
Biome governs formatting and linting; its rules live in biome.json. Run
pnpm fix&pnpm lintbefore committing, ensure there are no linting errors
Files:
apps/dashboard/src/app/bridge/buy-widget/layout.tsxapps/dashboard/src/@/constants/public-envs.tsapps/dashboard/src/app/bridge/buy-widget/page.tsxapps/dashboard/next.config.tsapps/dashboard/src/app/bridge/buy-widget/BuyWidgetEmbed.client.tsx
apps/{dashboard,playground}/**/*.{tsx,ts}
📄 CodeRabbit inference engine (AGENTS.md)
apps/{dashboard,playground}/**/*.{tsx,ts}: Import UI primitives from @/components/ui/_ (Button, Input, Select, Tabs, Card, Sidebar, Badge, Separator) in Dashboard and Playground apps
Use NavLink for internal navigation so active states are handled automatically
Use Tailwind CSS for styling – no inline styles or CSS modules
Merge class names with cn() from @/lib/utils to keep conditional logic readable
Stick to design tokens for styling: backgrounds (bg-card), borders (border-border), muted text (text-muted-foreground), etc.
Server Components: Read cookies/headers with next/headers, access server-only environment variables or secrets, perform heavy data fetching, implement redirect logic with redirect() from next/navigation, and start files with import 'server-only'; to prevent client bundling
Client Components: Begin files with 'use client'; before imports, handle interactive UI relying on React hooks (useState, useEffect, React Query, wallet hooks), access browser APIs (localStorage, window, IntersectionObserver, etc.), and support fast transitions with client-side data prefetching
For client-side data fetching: Wrap calls in React Query (@tanstack/react-query), use descriptive and stable queryKeys for cache hits, configure staleTime / cacheTime based on freshness requirements (default ≥ 60 s), and keep tokens secret by calling internal API routes or server actions
Files:
apps/dashboard/src/app/bridge/buy-widget/layout.tsxapps/dashboard/src/@/constants/public-envs.tsapps/dashboard/src/app/bridge/buy-widget/page.tsxapps/dashboard/next.config.tsapps/dashboard/src/app/bridge/buy-widget/BuyWidgetEmbed.client.tsx
apps/{dashboard,playground}/**/*.{ts,tsx}
📄 CodeRabbit inference engine (AGENTS.md)
apps/{dashboard,playground}/**/*.{ts,tsx}: For server-side data fetching: Always call getAuthToken() to retrieve the JWT from cookies and inject the token as an Authorization: Bearer header – never embed it in the URL. Return typed results (Project[], User[], …) – avoid any
Never import posthog-js in server components; analytics reporting is client-side only
Files:
apps/dashboard/src/app/bridge/buy-widget/layout.tsxapps/dashboard/src/@/constants/public-envs.tsapps/dashboard/src/app/bridge/buy-widget/page.tsxapps/dashboard/next.config.tsapps/dashboard/src/app/bridge/buy-widget/BuyWidgetEmbed.client.tsx
**/*.{ts,tsx,js,jsx}
📄 CodeRabbit inference engine (AGENTS.md)
Lazy-import optional features; avoid top-level side-effects
Files:
apps/dashboard/src/app/bridge/buy-widget/layout.tsxapps/dashboard/src/@/constants/public-envs.tsapps/dashboard/src/app/bridge/buy-widget/page.tsxapps/dashboard/next.config.tsapps/dashboard/src/app/bridge/buy-widget/BuyWidgetEmbed.client.tsx
apps/dashboard/**/page.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/dashboard.mdc)
Use the
containerclass with amax-w-7xlcap for consistent page width
Files:
apps/dashboard/src/app/bridge/buy-widget/page.tsx
apps/dashboard/**/*.client.tsx
📄 CodeRabbit inference engine (.cursor/rules/dashboard.mdc)
apps/dashboard/**/*.client.tsx: Name component files after the component in PascalCase; append.client.tsxwhen the component is interactive
Client components must start with'use client';directive before imports
Files:
apps/dashboard/src/app/bridge/buy-widget/BuyWidgetEmbed.client.tsx
🧬 Code graph analysis (2)
apps/dashboard/src/app/bridge/buy-widget/page.tsx (4)
apps/dashboard/src/app/bridge/_common/parseQueryParams.ts (3)
parseQueryParams(3-11)onlyNumber(14-15)onlyAddress(13-13)apps/dashboard/src/app/bridge/_common/isValidCurrency.ts (1)
isValidCurrency(3-10)apps/dashboard/src/app/bridge/(general)/components/client/Providers.client.tsx (1)
BridgeProvidersLite(44-64)apps/dashboard/src/app/bridge/buy-widget/BuyWidgetEmbed.client.tsx (1)
BuyWidgetEmbed(9-86)
apps/dashboard/src/app/bridge/buy-widget/BuyWidgetEmbed.client.tsx (2)
apps/dashboard/src/@/constants/thirdweb.server.ts (1)
getConfiguredThirdwebClient(26-97)apps/dashboard/src/@/constants/public-envs.ts (1)
NEXT_PUBLIC_BUY_IFRAME_CLIENT_ID(54-55)
⏰ 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). (8)
- GitHub Check: Size
- GitHub Check: Build Packages
- GitHub Check: E2E Tests (pnpm, vite)
- GitHub Check: E2E Tests (pnpm, esbuild)
- GitHub Check: E2E Tests (pnpm, webpack)
- GitHub Check: Lint Packages
- GitHub Check: Unit Tests
- GitHub Check: Analyze (javascript)
🔇 Additional comments (7)
apps/dashboard/src/app/bridge/buy-widget/layout.tsx (1)
1-27: LGTM! Appropriate layout for iframe embed.The custom layout is well-suited for the iframe-embedded buy widget. While the coding guidelines recommend reusing
SidebarLayoutorFullWidthSidebarLayout, this is a legitimate special case where a minimal root layout without dashboard chrome is needed. The implementation correctly uses design tokens (bg-background,font-sans) and thecn()utility for class merging.apps/dashboard/next.config.ts (1)
200-217: LGTM! Consistent CSP configuration.The new CSP headers for
/bridge/buy-widgetand/bridge/buy-widget/:path*correctly mirror the existing pattern used for other widget routes. The use ofEmbedContentSecurityPolicywithframe-ancestors *;is appropriate for iframe embedding.apps/dashboard/src/@/constants/public-envs.ts (1)
54-55: LGTM! Consistent with existing iframe client ID pattern.The new environment variable follows the same pattern as other iframe client IDs (lines 45-52) and intentionally doesn't include a fallback, which is consistent with how other widget client IDs are handled.
apps/dashboard/src/app/bridge/buy-widget/page.tsx (1)
30-97: Query parameter parsing and component integration look solid.The page correctly uses Next.js 15's async
searchParamsAPI and properly validates/parses all query parameters before passing them toBuyWidgetEmbed. The theme fallback to"dark"and the handling of optional parameters are appropriate.apps/dashboard/src/app/bridge/buy-widget/BuyWidgetEmbed.client.tsx (3)
38-52: Good use of memoization for client and chain.The memoization prevents unnecessary re-initialization of the Thirdweb client and chain definition. The empty dependency array for
clientis correct since the client ID is a constant, andchainIdis properly listed as a dependency for thechainmemo.
7-7: The import is safe but the module naming is misleading.
getConfiguredThirdwebClientonly uses public environment variables (NEXT_PUBLIC_*) and third-party SDK functions; it does not invoke server-only APIs or secrets. In this usage,secretKeyis explicitlyundefined, making the client-side import secure.However, the
.server.tsfile extension suggests server-exclusive code (especially given the nearbythirdweb-client.server.tswhich properly imports"server-only"). SincegetConfiguredThirdwebClienthas no server-only dependencies, consider relocating it to a shared utility file (e.g.,@/constants/thirdweb.ts) to clarify that it works on both sides.
88-95: Add a comment documenting the intentional use of wildcard origin for third-party embed compatibility.The
sendMessageToParentfunction uses"*"as the target origin to enable embedding in any third-party site. This is intentional and acceptable since the messages contain only non-sensitive metadata: event type and user-facing error messages. Consider adding a JSDoc comment explaining this design choice:/** * Send a message to the parent window. Uses wildcard origin to support * embedding in any third-party site. Messages contain only non-sensitive * event metadata (success/error status), not user credentials or secrets. */ function sendMessageToParent(content: object) { try { window.parent.postMessage(content, "*"); } catch (error) { console.error("Failed to send post message to parent window"); console.error(error); } }
size-limit report 📦
|
Merge activity
|
<!--
## title your PR with this format: "[SDK/Dashboard/Portal] Feature/Fix: Concise title for the changes"
If you did not copy the branch name from Linear, paste the issue tag here (format is TEAM-0000):
## Notes for the reviewer
Anything important to call out? Be sure to also clarify these in your comments.
## How to test
Unit tests, playground, etc.
-->
<!-- start pr-codex -->
---
## PR-Codex overview
This PR introduces a new `BuyWidget` feature, allowing users to purchase crypto tokens using various payment methods. It adds necessary environment variables, updates configuration for security policies, and implements the layout and functionality for the `BuyWidgetEmbed` component.
### Detailed summary
- Added `NEXT_PUBLIC_BUY_IFRAME_CLIENT_ID` to `public-envs.ts`.
- Updated `next.config.ts` with new Content Security Policy headers for `/bridge/buy-widget`.
- Created `BuyWidgetLayout` component in `layout.tsx` for the buy widget page.
- Implemented `BuyWidgetEmbed` component in `BuyWidgetEmbed.client.tsx` for handling crypto purchases.
- Enhanced `page.tsx` to manage search parameters and integrate `BuyWidgetEmbed`.
> ✨ Ask PR-Codex anything about this PR by commenting with `/codex {your question}`
<!-- end pr-codex -->
<!-- This is an auto-generated comment: release notes by coderabbit.ai -->
## Summary by CodeRabbit
## Release Notes
* **New Features**
* Added a new buy widget enabling direct cryptocurrency purchases with configurable payment methods (crypto and card) and multi-currency support
* Implemented personalization options including custom titles, descriptions, images, and button labels
* Enhanced security infrastructure to support the new widget functionality
<sub>✏️ Tip: You can customize this high-level summary in your review settings.</sub>
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
b0560e7 to
4fc02b3
Compare
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: 3
🤖 Fix all issues with AI agents
In @apps/dashboard/src/app/bridge/buy-widget/BuyWidgetEmbed.client.tsx:
- Around line 88-95: The sendMessageToParent function currently posts messages
with "*" which is insecure; change it to validate and use a restricted target
origin: determine the allowed parent origin (prefer a configured constant or
prop, else parse and validate document.referrer against an allowlist) and pass
that origin to window.parent.postMessage; if the origin is missing or not
allowed, do not send and log a warning. Ensure you update the
sendMessageToParent function name reference and its error handling to include
the origin used and any validation failures in the console or logger.
- Line 7: The client component BuyWidgetEmbed.client.tsx imports
getConfiguredThirdwebClient from a .server module which breaks the server/client
boundary; replace that import by either creating a client-safe initializer
(e.g., getConfiguredThirdwebClient.client.ts that exports a browser-safe
function) and import that, move shared safe logic into a non-.server utility
used by both, or initialize the Thirdweb client directly inside
BuyWidgetEmbed.client.tsx using createThirdwebClient from the thirdweb SDK;
update references to getConfiguredThirdwebClient in this file to use the new
client-safe function name or direct initialization and remove any server-only
imports.
📜 Review details
Configuration used: Organization 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 (5)
apps/dashboard/next.config.tsapps/dashboard/src/@/constants/public-envs.tsapps/dashboard/src/app/bridge/buy-widget/BuyWidgetEmbed.client.tsxapps/dashboard/src/app/bridge/buy-widget/layout.tsxapps/dashboard/src/app/bridge/buy-widget/page.tsx
🚧 Files skipped from review as they are similar to previous changes (1)
- apps/dashboard/next.config.ts
🧰 Additional context used
📓 Path-based instructions (11)
**/*.{ts,tsx}
📄 CodeRabbit inference engine (CLAUDE.md)
**/*.{ts,tsx}: Write idiomatic TypeScript with explicit function declarations and return types
Limit each TypeScript 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 in TypeScript
Avoidanyandunknownin TypeScript unless unavoidable; narrow generics when possible
Choose composition over inheritance; leverage utility types (Partial,Pick, etc.) in TypeScript
**/*.{ts,tsx}: Write idiomatic TypeScript with explicit function declarations and return types
Limit each file to one stateless, single-responsibility function for clarity and testability
Re-use shared types from @/types or local types.ts barrel exports
Prefer type aliases over interface except for nominal shapes
Avoid any and unknown unless unavoidable; narrow generics whenever possible
Choose composition over inheritance; leverage utility types (Partial, Pick, etc.)
Comment only ambiguous logic in TypeScript files; avoid restating TypeScript types and signatures in prose
Files:
apps/dashboard/src/app/bridge/buy-widget/layout.tsxapps/dashboard/src/app/bridge/buy-widget/page.tsxapps/dashboard/src/app/bridge/buy-widget/BuyWidgetEmbed.client.tsxapps/dashboard/src/@/constants/public-envs.ts
apps/{dashboard,playground-web}/src/**/*.{ts,tsx}
📄 CodeRabbit inference engine (CLAUDE.md)
apps/{dashboard,playground-web}/src/**/*.{ts,tsx}: Import UI component primitives from@/components/ui/*(Button, Input, Select, Tabs, Card, Sidebar, Badge, Separator) in dashboard and playground
Use Tailwind CSS only – no inline styles or CSS modules in dashboard and playground
Usecn()from@/lib/utilsfor conditional Tailwind class merging
Use design system tokens for styling (backgrounds:bg-card, borders:border-border, muted text:text-muted-foreground)
ExposeclassNameprop on root element for component overrides
Files:
apps/dashboard/src/app/bridge/buy-widget/layout.tsxapps/dashboard/src/app/bridge/buy-widget/page.tsxapps/dashboard/src/app/bridge/buy-widget/BuyWidgetEmbed.client.tsxapps/dashboard/src/@/constants/public-envs.ts
apps/dashboard/src/**/*.{ts,tsx}
📄 CodeRabbit inference engine (CLAUDE.md)
apps/dashboard/src/**/*.{ts,tsx}: UseNavLinkfor internal navigation with automatic active states in dashboard
Start server component files withimport "server-only";in Next.js
Read cookies/headers withnext/headersin server components
Access server-only environment variables in server components
Perform heavy data fetching in server components
Implement redirect logic withredirect()fromnext/navigationin server components
Begin client component files with'use client';directive in Next.js
Handle interactive UI with React hooks (useState,useEffect, React Query, wallet hooks) in client components
Access browser APIs (localStorage,window,IntersectionObserver) in client components
Support fast transitions with prefetched data in client components
Always callgetAuthToken()to retrieve JWT from cookies on server side
UseAuthorization: Bearerheader for API calls – never embed tokens in URLs
Return typed results (Project[],User[]) from server-side data fetches – avoidany
Wrap client-side API calls in React Query (@tanstack/react-query)
Use descriptive, stablequeryKeysin React Query for 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 – only use analytics client-side
Files:
apps/dashboard/src/app/bridge/buy-widget/layout.tsxapps/dashboard/src/app/bridge/buy-widget/page.tsxapps/dashboard/src/app/bridge/buy-widget/BuyWidgetEmbed.client.tsxapps/dashboard/src/@/constants/public-envs.ts
apps/dashboard/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/dashboard.mdc)
apps/dashboard/**/*.{ts,tsx}: Always import from the central UI library under@/components/ui/*for reusable core UI components likeButton,Input,Select,Tabs,Card,Sidebar,Separator,Badge
UseNavLinkfrom@/components/ui/NavLinkfor internal navigation to ensure active states are handled automatically
For notices and skeletons, rely onAnnouncementBanner,GenericLoadingPage, andEmptyStateCardcomponents
Import icons fromlucide-reactor the project-specific…/iconsexports; never embed raw SVG
Keep components pure; fetch data outside using server components or hooks and pass it down via props
Use Tailwind CSS as the styling system; avoid inline styles or CSS modules
Merge class names withcnfrom@/lib/utilsto keep conditional logic readable
Stick to design tokens: usebg-card,border-border,text-muted-foregroundand other Tailwind variables instead of hard-coded colors
Use spacing utilities (px-*,py-*,gap-*) instead of custom margins
Follow mobile-first responsive design with Tailwind helpers (max-sm,md,lg,xl)
Never hard-code colors; always use Tailwind variables
Combine class names viacn, and exposeclassNameprop if useful in components
Use React Query (@tanstack/react-query) for all client-side data fetching with typed hooks
Files:
apps/dashboard/src/app/bridge/buy-widget/layout.tsxapps/dashboard/src/app/bridge/buy-widget/page.tsxapps/dashboard/src/app/bridge/buy-widget/BuyWidgetEmbed.client.tsxapps/dashboard/src/@/constants/public-envs.ts
apps/dashboard/**/layout.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/dashboard.mdc)
apps/dashboard/**/layout.{ts,tsx}: ReuseSidebarLayoutorFullWidthSidebarLayoutfrom@/components/blocks/SidebarLayoutfor all layouts
Export default async functions without'use client';in server components; they run on the Node edge
Files:
apps/dashboard/src/app/bridge/buy-widget/layout.tsx
**/*.{js,jsx,ts,tsx,json}
📄 CodeRabbit inference engine (AGENTS.md)
Biome governs formatting and linting; its rules live in biome.json. Run
pnpm fix&pnpm lintbefore committing, ensure there are no linting errors
Files:
apps/dashboard/src/app/bridge/buy-widget/layout.tsxapps/dashboard/src/app/bridge/buy-widget/page.tsxapps/dashboard/src/app/bridge/buy-widget/BuyWidgetEmbed.client.tsxapps/dashboard/src/@/constants/public-envs.ts
apps/{dashboard,playground}/**/*.{tsx,ts}
📄 CodeRabbit inference engine (AGENTS.md)
apps/{dashboard,playground}/**/*.{tsx,ts}: Import UI primitives from @/components/ui/_ (Button, Input, Select, Tabs, Card, Sidebar, Badge, Separator) in Dashboard and Playground apps
Use NavLink for internal navigation so active states are handled automatically
Use Tailwind CSS for styling – no inline styles or CSS modules
Merge class names with cn() from @/lib/utils to keep conditional logic readable
Stick to design tokens for styling: backgrounds (bg-card), borders (border-border), muted text (text-muted-foreground), etc.
Server Components: Read cookies/headers with next/headers, access server-only environment variables or secrets, perform heavy data fetching, implement redirect logic with redirect() from next/navigation, and start files with import 'server-only'; to prevent client bundling
Client Components: Begin files with 'use client'; before imports, handle interactive UI relying on React hooks (useState, useEffect, React Query, wallet hooks), access browser APIs (localStorage, window, IntersectionObserver, etc.), and support fast transitions with client-side data prefetching
For client-side data fetching: Wrap calls in React Query (@tanstack/react-query), use descriptive and stable queryKeys for cache hits, configure staleTime / cacheTime based on freshness requirements (default ≥ 60 s), and keep tokens secret by calling internal API routes or server actions
Files:
apps/dashboard/src/app/bridge/buy-widget/layout.tsxapps/dashboard/src/app/bridge/buy-widget/page.tsxapps/dashboard/src/app/bridge/buy-widget/BuyWidgetEmbed.client.tsxapps/dashboard/src/@/constants/public-envs.ts
apps/{dashboard,playground}/**/*.{ts,tsx}
📄 CodeRabbit inference engine (AGENTS.md)
apps/{dashboard,playground}/**/*.{ts,tsx}: For server-side data fetching: Always call getAuthToken() to retrieve the JWT from cookies and inject the token as an Authorization: Bearer header – never embed it in the URL. Return typed results (Project[], User[], …) – avoid any
Never import posthog-js in server components; analytics reporting is client-side only
Files:
apps/dashboard/src/app/bridge/buy-widget/layout.tsxapps/dashboard/src/app/bridge/buy-widget/page.tsxapps/dashboard/src/app/bridge/buy-widget/BuyWidgetEmbed.client.tsxapps/dashboard/src/@/constants/public-envs.ts
**/*.{ts,tsx,js,jsx}
📄 CodeRabbit inference engine (AGENTS.md)
Lazy-import optional features; avoid top-level side-effects
Files:
apps/dashboard/src/app/bridge/buy-widget/layout.tsxapps/dashboard/src/app/bridge/buy-widget/page.tsxapps/dashboard/src/app/bridge/buy-widget/BuyWidgetEmbed.client.tsxapps/dashboard/src/@/constants/public-envs.ts
apps/dashboard/**/page.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/dashboard.mdc)
Use the
containerclass with amax-w-7xlcap for consistent page width
Files:
apps/dashboard/src/app/bridge/buy-widget/page.tsx
apps/dashboard/**/*.client.tsx
📄 CodeRabbit inference engine (.cursor/rules/dashboard.mdc)
apps/dashboard/**/*.client.tsx: Name component files after the component in PascalCase; append.client.tsxwhen the component is interactive
Client components must start with'use client';directive before imports
Files:
apps/dashboard/src/app/bridge/buy-widget/BuyWidgetEmbed.client.tsx
🧬 Code graph analysis (2)
apps/dashboard/src/app/bridge/buy-widget/page.tsx (4)
apps/dashboard/src/app/bridge/_common/parseQueryParams.ts (3)
parseQueryParams(3-11)onlyNumber(14-15)onlyAddress(13-13)apps/dashboard/src/app/bridge/_common/isValidCurrency.ts (1)
isValidCurrency(3-10)apps/dashboard/src/app/bridge/(general)/components/client/Providers.client.tsx (1)
BridgeProvidersLite(44-64)apps/dashboard/src/app/bridge/buy-widget/BuyWidgetEmbed.client.tsx (1)
BuyWidgetEmbed(9-86)
apps/dashboard/src/app/bridge/buy-widget/BuyWidgetEmbed.client.tsx (2)
apps/dashboard/src/@/constants/thirdweb.server.ts (1)
getConfiguredThirdwebClient(26-97)apps/dashboard/src/@/constants/public-envs.ts (1)
NEXT_PUBLIC_BUY_IFRAME_CLIENT_ID(54-55)
⏰ 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). (8)
- GitHub Check: E2E Tests (pnpm, vite)
- GitHub Check: Unit Tests
- GitHub Check: E2E Tests (pnpm, webpack)
- GitHub Check: E2E Tests (pnpm, esbuild)
- GitHub Check: Build Packages
- GitHub Check: Lint Packages
- GitHub Check: Size
- GitHub Check: Analyze (javascript)
🔇 Additional comments (2)
apps/dashboard/src/@/constants/public-envs.ts (1)
54-55: LGTM! Environment variable export follows existing patterns.The new
NEXT_PUBLIC_BUY_IFRAME_CLIENT_IDexport is consistent with other iframe client ID constants in this file.apps/dashboard/src/app/bridge/buy-widget/page.tsx (1)
76-97: LGTM! Component integration and prop forwarding is correct.The page properly wraps
BuyWidgetEmbedwithBridgeProvidersLite, maintains theme consistency between the provider and the widget, and forwards all parsed query parameters correctly.
| import { type Address, defineChain } from "thirdweb"; | ||
| import { BuyWidget, type SupportedFiatCurrency } from "thirdweb/react"; | ||
| import { NEXT_PUBLIC_BUY_IFRAME_CLIENT_ID } from "@/constants/public-envs"; | ||
| import { getConfiguredThirdwebClient } from "@/constants/thirdweb.server"; |
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.
Avoid importing .server modules in client components.
Importing getConfiguredThirdwebClient from @/constants/thirdweb.server in a client component violates the server/client boundary. The .server suffix indicates this module is intended for server-side use only and may contain server-specific logic or configurations.
Consider either:
- Creating a client-specific version of the Thirdweb client initialization (e.g.,
getConfiguredThirdwebClient.client.ts) - Moving the client initialization logic to a shared utility that's explicitly safe for both environments
- Initializing the client directly in this component using
createThirdwebClientfrom the thirdweb SDK
Alternative: Direct client initialization
-import { getConfiguredThirdwebClient } from "@/constants/thirdweb.server";
+import { createThirdwebClient } from "thirdweb";
export function BuyWidgetEmbed({
// ...props
}) {
const client = useMemo(
() =>
- getConfiguredThirdwebClient({
+ createThirdwebClient({
clientId: NEXT_PUBLIC_BUY_IFRAME_CLIENT_ID,
- secretKey: undefined,
- teamId: undefined,
}),
[],
);Committable suggestion skipped: line range outside the PR's diff.
🤖 Prompt for AI Agents
In @apps/dashboard/src/app/bridge/buy-widget/BuyWidgetEmbed.client.tsx at line
7, The client component BuyWidgetEmbed.client.tsx imports
getConfiguredThirdwebClient from a .server module which breaks the server/client
boundary; replace that import by either creating a client-safe initializer
(e.g., getConfiguredThirdwebClient.client.ts that exports a browser-safe
function) and import that, move shared safe logic into a non-.server utility
used by both, or initialize the Thirdweb client directly inside
BuyWidgetEmbed.client.tsx using createThirdwebClient from the thirdweb SDK;
update references to getConfiguredThirdwebClient in this file to use the new
client-safe function name or direct initialization and remove any server-only
imports.
| function sendMessageToParent(content: object) { | ||
| try { | ||
| window.parent.postMessage(content, "*"); | ||
| } catch (error) { | ||
| console.error("Failed to send post message to parent window"); | ||
| console.error(error); | ||
| } | ||
| } |
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.
Security: Restrict postMessage target origin.
Using a wildcard origin "*" in window.parent.postMessage() is a security risk. It allows any parent window from any origin to receive the success/error messages, which could leak sensitive information about user transactions to malicious iframes or parent windows.
🔒 Recommended fix: Validate and restrict target origin
-function sendMessageToParent(content: object) {
+function sendMessageToParent(content: object) {
+ // Only send to expected parent origins
+ const allowedOrigins = [
+ 'https://thirdweb.com',
+ 'https://dashboard.thirdweb.com',
+ // Add other allowed origins
+ ];
+
+ const parentOrigin = document.referrer ? new URL(document.referrer).origin : '*';
+
try {
- window.parent.postMessage(content, "*");
+ if (allowedOrigins.includes(parentOrigin) || parentOrigin === window.location.origin) {
+ window.parent.postMessage(content, parentOrigin);
+ } else {
+ console.warn('Parent origin not in allowlist:', parentOrigin);
+ }
} catch (error) {
console.error("Failed to send post message to parent window");
console.error(error);
}
}Alternatively, if the expected parent origin is known at build time or can be passed as a query parameter, use that instead of document.referrer.
🤖 Prompt for AI Agents
In @apps/dashboard/src/app/bridge/buy-widget/BuyWidgetEmbed.client.tsx around
lines 88 - 95, The sendMessageToParent function currently posts messages with
"*" which is insecure; change it to validate and use a restricted target origin:
determine the allowed parent origin (prefer a configured constant or prop, else
parse and validate document.referrer against an allowlist) and pass that origin
to window.parent.postMessage; if the origin is missing or not allowed, do not
send and log a warning. Ensure you update the sendMessageToParent function name
reference and its error handling to include the origin used and any validation
failures in the console or logger.
| export default function BuyWidgetLayout({ | ||
| children, | ||
| }: { | ||
| children: React.ReactNode; | ||
| }) { | ||
| return ( | ||
| <html lang="en" suppressHydrationWarning> | ||
| <body | ||
| className={cn( | ||
| "min-h-dvh bg-background font-sans antialiased flex flex-col", | ||
| fontSans.variable, | ||
| )} | ||
| > | ||
| {children} | ||
| </body> | ||
| </html> | ||
| ); | ||
| } |
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.
Nested layouts must not declare <html> and <body> tags.
In Next.js App Router, only the root app/layout.tsx should contain <html> and <body> elements. Nested route layouts should only wrap {children} directly. This structure will cause hydration errors and conflicts with the parent layout.
Additionally, per coding guidelines, layouts should reuse SidebarLayout or FullWidthSidebarLayout from @/components/blocks/SidebarLayout.
🔧 Proposed fix: Remove html/body wrapper
-export default function BuyWidgetLayout({
+export default async function BuyWidgetLayout({
children,
}: {
children: React.ReactNode;
}) {
- return (
- <html lang="en" suppressHydrationWarning>
- <body
- className={cn(
- "min-h-dvh bg-background font-sans antialiased flex flex-col",
- fontSans.variable,
- )}
- >
- {children}
- </body>
- </html>
- );
+ return <>{children}</>;
}If custom styling is needed, wrap {children} in a <div> with appropriate classes instead of redefining the document structure.
Based on coding guidelines: "Reuse SidebarLayout or FullWidthSidebarLayout from @/components/blocks/SidebarLayout for all layouts" and "Export default async functions without 'use client'; in server components"
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| export default function BuyWidgetLayout({ | |
| children, | |
| }: { | |
| children: React.ReactNode; | |
| }) { | |
| return ( | |
| <html lang="en" suppressHydrationWarning> | |
| <body | |
| className={cn( | |
| "min-h-dvh bg-background font-sans antialiased flex flex-col", | |
| fontSans.variable, | |
| )} | |
| > | |
| {children} | |
| </body> | |
| </html> | |
| ); | |
| } | |
| export default async function BuyWidgetLayout({ | |
| children, | |
| }: { | |
| children: React.ReactNode; | |
| }) { | |
| return <>{children}</>; | |
| } |

PR-Codex overview
This PR introduces a new
BuyWidgetfeature to the dashboard, allowing users to purchase crypto tokens using various payment methods. It adds necessary constants, components, and configurations to support this functionality.Detailed summary
NEXT_PUBLIC_BUY_IFRAME_CLIENT_IDinpublic-envs.ts.next.config.tswith new routes and content security policies for the buy widget.BuyWidgetLayoutcomponent inlayout.tsx.BuyWidgetEmbedcomponent with client configuration and messaging.page.tsxto handle parameters and render theBuyWidgetEmbed.Summary by CodeRabbit
New Features
Security
✏️ Tip: You can customize this high-level summary in your review settings.