-
Notifications
You must be signed in to change notification settings - Fork 403
feat(clerk-js,clerk-react): Support Base authentication #6556
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.
|
🦋 Changeset detectedLatest commit: 1732dca The changes in this PR will be included in the next version bump. This PR includes changesets to release 22 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 Base wallet authentication across the frontend SDK: new authenticateWithBase APIs and types, Base provider/strategy in registries, web3 utilities to lazy-load @base-org/account and generate signatures, integration into elements/machines/hooks, a build chunk for the SDK, and a release changeset. No existing provider behavior removed. Changes
Sequence Diagram(s)sequenceDiagram
participant App
participant IsomorphicClerk
participant ClerkJS
participant BaseSDK
participant Backend
App->>IsomorphicClerk: authenticateWithBase(params)
IsomorphicClerk->>ClerkJS: authenticateWithBase(params)
ClerkJS->>BaseSDK: dynamic import @base-org/account & getProvider()
Note right of BaseSDK #dfefff: (async) returns provider / address
ClerkJS->>BaseSDK: request identifier & sign nonce
BaseSDK-->>ClerkJS: signature
ClerkJS->>Backend: POST authenticate (strategy: web3_base_signature, signature, identifier)
Backend-->>ClerkJS: auth token / session
ClerkJS-->>IsomorphicClerk: resolve
IsomorphicClerk-->>App: done
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Assessment against linked issues
Assessment against linked issues: Out-of-scope changes
📜 Recent review detailsConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro 💡 Knowledge Base configuration:
You can enable these sources in your CodeRabbit configuration. 📒 Files selected for processing (2)
🚧 Files skipped from review as they are similar to previous changes (2)
⏰ 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). (6)
✨ Finishing Touches
🧪 Generate unit tests
🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. CodeRabbit Commands (Invoked using PR/Issue comments)Type Other keywords and placeholders
Status, Documentation and Community
|
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
🔭 Outside diff range comments (1)
packages/clerk-js/src/core/resources/SignIn.ts (1)
145-154: Add SignIn.prepareFirstFactor support for 'web3_base_account_signature'When calling authenticateWithWeb3 for Base Account, we end up invoking prepareFirstFactor with the web3 factor returned from FAPI. Since 'web3_base_account_signature' is not included in this switch, clerkInvalidStrategy will be thrown and the flow will fail.
Add a case mirroring the other web3 providers.
Apply this diff to include Base Account:
case 'web3_coinbase_wallet_signature': config = { web3WalletId: factor.web3WalletId } as Web3SignatureConfig; break; case 'web3_okx_wallet_signature': config = { web3WalletId: factor.web3WalletId } as Web3SignatureConfig; break; + case 'web3_base_account_signature': + config = { web3WalletId: factor.web3WalletId } as Web3SignatureConfig; + break;
🧹 Nitpick comments (10)
packages/types/src/signIn.ts (1)
117-118: Add JSDoc for the new public API methodPublic APIs must be documented. Please add a short JSDoc describing what this method does and what it returns.
Apply this diff:
authenticateWithOKXWallet: () => Promise<SignInResource>; + /** + * Authenticate the current sign-in using the Base Account provider + * via a web3 signature flow. + * Returns the updated SignInResource on success. + */ authenticateWithBaseAccount: () => Promise<SignInResource>;.changeset/silent-insects-cheat.md (1)
1-9: Enrich the changeset description for downstream consumersConsider adding a brief summary of the public API surface changes and a one-line migration/use note (e.g., newly added methods and provider key/strategy). This helps package consumers understand what changed without scanning the PR.
For example:
- Adds Base Account as a web3 provider: provider = "base_account", strategy = "web3_base_account_signature".
- New public APIs:
- Clerk.authenticateWithBaseAccount(params?)
- SignIn.authenticateWithBaseAccount()
- SignUp.authenticateWithBaseAccount(params?)
- Docs: Add Base Account auth guide (link).
packages/clerk-js/src/core/resources/SignIn.ts (1)
364-371: Expose minimal JSDoc for the new public APIThe new public method is missing JSDoc. For consistency with our guidelines (public APIs documented) and discoverability, add a brief description and return type info.
Example:
+ /** + * Authenticates the user using Base Account. + * Uses `web3_base_account_signature` strategy under the hood. + */ public authenticateWithBaseAccount = async (): Promise<SignInResource> => {packages/clerk-js/src/core/clerk.ts (1)
2171-2181: Prefer provider-based branching for consistencyYou compute
providerabove; then branch onstrategyonly for Base while usingproviderfor the other wallets. Useprovider === 'base_account'for consistency/readability.Apply this diff:
- const generateSignature = - provider === 'metamask' - ? generateSignatureWithMetamask - : strategy === 'web3_base_account_signature' - ? generateSignatureWithBaseAccount - : provider === 'coinbase_wallet' - ? generateSignatureWithCoinbaseWallet - : generateSignatureWithOKXWallet; + const generateSignature = + provider === 'metamask' + ? generateSignatureWithMetamask + : provider === 'base_account' + ? generateSignatureWithBaseAccount + : provider === 'coinbase_wallet' + ? generateSignatureWithCoinbaseWallet + : generateSignatureWithOKXWallet;packages/clerk-js/src/core/resources/SignUp.ts (2)
261-274: SignUp Base Account flow mirrors existing providers (LGTM)The new method follows the established pattern: fetch identifier, delegate to authenticateWithWeb3 with the correct strategy, and forward metadata/consent. Looks correct.
Consider adding a one-line JSDoc to align with our “All public APIs must be documented” guideline.
181-229: Optional: Confirm whether Base Account needs a “retry on user rejected” behaviorThe Coinbase Wallet flow retries on error code 4001. If Base Account SDK shares the same behavior, we might want to extend the retry condition accordingly; if not, ignore.
Would you like me to add a guarded retry for Base if the SDK signals a transient, user-first-time setup rejection?
packages/clerk-js/src/utils/web3.ts (4)
61-63: Public util added: add JSDoc and test coverageImplementation is fine. Please document this public API and add tests that cover:
- Returns first address when provider resolves
- Returns empty string when provider is unavailable or user rejects
Suggested JSDoc:
/** * Returns the first EIP-1193 account for the Base Account provider or '' if unavailable. * Note: resolves to '' when the provider cannot be loaded or no accounts are returned. */
82-84: Public util added: add JSDoc and test coverageLooks good. Please document and add tests validating:
- Successful signature generation for a given nonce and identifier
- Empty string fallback when provider import fails (consistent with existing behavior)
Suggested JSDoc:
/** * Signs the given nonce with the Base Account provider using personal_sign. * Returns '' if the provider cannot be loaded. */
28-30: Avoid local type duplication and potential confusion with GenerateSignatureParamsThis file defines a local
type GenerateSignatureParamswhile@clerk/typesalready exposesGenerateSignatureParams(with an optional provider). To reduce confusion and ensure consistency, import and derive from the canonical type:-import type { Web3Provider } from '@clerk/types'; +import type { Web3Provider, GenerateSignatureParams as PublicGenerateSignatureParams } from '@clerk/types'; -type GenerateWeb3SignatureParams = GenerateSignatureParams & { +type GenerateWeb3SignatureParams = Omit<PublicGenerateSignatureParams, 'provider'> & { provider: Web3Provider; }; - -type GenerateSignatureParams = { - identifier: string; - nonce: string; -}; +type GenerateSignatureParams = Omit<PublicGenerateSignatureParams, 'provider'>;This keeps the public and internal signatures aligned and avoids shadowing.
Also applies to: 65-68
101-111: Consider SSR/RHC parity and developer-facing warnings for Base AccountCoinbase has an environment guard using
__BUILD_DISABLE_RHC__plus a warning. For parity and clearer developer signals, consider mirroring this pattern for Base Account:
- Gate Base Account when that flag is enabled (if intended).
- Emit a consistent warning when the provider cannot be loaded (e.g., missing dependency, SSR, CSP).
Example:
if (__BUILD_DISABLE_RHC__) { clerkUnsupportedEnvironmentWarning('Base Account'); return null; }
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (11)
.changeset/silent-insects-cheat.md(1 hunks)packages/clerk-js/src/core/clerk.ts(3 hunks)packages/clerk-js/src/core/resources/SignIn.ts(2 hunks)packages/clerk-js/src/core/resources/SignUp.ts(2 hunks)packages/clerk-js/src/utils/web3.ts(3 hunks)packages/react/src/isomorphicClerk.ts(2 hunks)packages/shared/src/web3.ts(1 hunks)packages/types/src/clerk.ts(2 hunks)packages/types/src/signIn.ts(1 hunks)packages/types/src/signUp.ts(1 hunks)packages/types/src/web3.ts(2 hunks)
🧰 Additional context used
📓 Path-based instructions (8)
**/*.{js,jsx,ts,tsx}
📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)
**/*.{js,jsx,ts,tsx}: All code must pass ESLint checks with the project's configuration
Follow established naming conventions (PascalCase for components, camelCase for variables)
Maintain comprehensive JSDoc comments for public APIs
Use dynamic imports for optional features
All public APIs must be documented with JSDoc
Provide meaningful error messages to developers
Include error recovery suggestions where applicable
Log errors appropriately for debugging
Lazy load components and features when possible
Implement proper caching strategies
Use efficient data structures and algorithms
Profile and optimize critical paths
Validate all inputs and sanitize outputs
Implement proper logging with different levels
Files:
packages/types/src/signUp.tspackages/shared/src/web3.tspackages/types/src/signIn.tspackages/clerk-js/src/core/resources/SignIn.tspackages/types/src/clerk.tspackages/clerk-js/src/utils/web3.tspackages/clerk-js/src/core/resources/SignUp.tspackages/clerk-js/src/core/clerk.tspackages/react/src/isomorphicClerk.tspackages/types/src/web3.ts
**/*.{js,jsx,ts,tsx,json,css,scss,md,yaml,yml}
📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)
Use Prettier for consistent code formatting
Files:
packages/types/src/signUp.tspackages/shared/src/web3.tspackages/types/src/signIn.tspackages/clerk-js/src/core/resources/SignIn.tspackages/types/src/clerk.tspackages/clerk-js/src/utils/web3.tspackages/clerk-js/src/core/resources/SignUp.tspackages/clerk-js/src/core/clerk.tspackages/react/src/isomorphicClerk.tspackages/types/src/web3.ts
packages/**/*.{ts,tsx}
📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)
TypeScript is required for all packages
Files:
packages/types/src/signUp.tspackages/shared/src/web3.tspackages/types/src/signIn.tspackages/clerk-js/src/core/resources/SignIn.tspackages/types/src/clerk.tspackages/clerk-js/src/utils/web3.tspackages/clerk-js/src/core/resources/SignUp.tspackages/clerk-js/src/core/clerk.tspackages/react/src/isomorphicClerk.tspackages/types/src/web3.ts
packages/**/*.{ts,tsx,d.ts}
📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)
Packages should export TypeScript types alongside runtime code
Files:
packages/types/src/signUp.tspackages/shared/src/web3.tspackages/types/src/signIn.tspackages/clerk-js/src/core/resources/SignIn.tspackages/types/src/clerk.tspackages/clerk-js/src/utils/web3.tspackages/clerk-js/src/core/resources/SignUp.tspackages/clerk-js/src/core/clerk.tspackages/react/src/isomorphicClerk.tspackages/types/src/web3.ts
**/*.{ts,tsx}
📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)
Use proper TypeScript error types
**/*.{ts,tsx}: Always define explicit return types for functions, especially public APIs
Use proper type annotations for variables and parameters where inference isn't clear
Avoidanytype - preferunknownwhen type is uncertain, then narrow with type guards
Useinterfacefor object shapes that might be extended
Usetypefor unions, primitives, and computed types
Preferreadonlyproperties for immutable data structures
Useprivatefor internal implementation details
Useprotectedfor inheritance hierarchies
Usepublicexplicitly for clarity in public APIs
Preferreadonlyfor properties that shouldn't change after construction
Prefer composition and interfaces over deep inheritance chains
Use mixins for shared behavior across unrelated classes
Implement dependency injection for loose coupling
Let TypeScript infer when types are obvious
Useconst assertionsfor literal types:as const
Usesatisfiesoperator for type checking without widening
Use mapped types for transforming object types
Use conditional types for type-level logic
Leverage template literal types for string manipulation
Use ES6 imports/exports consistently
Use default exports sparingly, prefer named exports
Use type-only imports:import type { ... } from ...
Noanytypes without justification
Proper error handling with typed errors
Consistent use ofreadonlyfor immutable data
Proper generic constraints
No unused type parameters
Proper use of utility types instead of manual type construction
Type-only imports where possible
Proper tree-shaking friendly exports
No circular dependencies
Efficient type computations (avoid deep recursion)
Files:
packages/types/src/signUp.tspackages/shared/src/web3.tspackages/types/src/signIn.tspackages/clerk-js/src/core/resources/SignIn.tspackages/types/src/clerk.tspackages/clerk-js/src/utils/web3.tspackages/clerk-js/src/core/resources/SignUp.tspackages/clerk-js/src/core/clerk.tspackages/react/src/isomorphicClerk.tspackages/types/src/web3.ts
**/*.{js,ts,tsx,jsx}
📄 CodeRabbit Inference Engine (.cursor/rules/monorepo.mdc)
Support multiple Clerk environment variables (CLERK_, NEXT_PUBLIC_CLERK_, etc.) for configuration.
Files:
packages/types/src/signUp.tspackages/shared/src/web3.tspackages/types/src/signIn.tspackages/clerk-js/src/core/resources/SignIn.tspackages/types/src/clerk.tspackages/clerk-js/src/utils/web3.tspackages/clerk-js/src/core/resources/SignUp.tspackages/clerk-js/src/core/clerk.tspackages/react/src/isomorphicClerk.tspackages/types/src/web3.ts
**/*
⚙️ CodeRabbit Configuration File
If there are no tests added or modified as part of the PR, please suggest that tests be added to cover the changes.
Files:
packages/types/src/signUp.tspackages/shared/src/web3.tspackages/types/src/signIn.tspackages/clerk-js/src/core/resources/SignIn.tspackages/types/src/clerk.tspackages/clerk-js/src/utils/web3.tspackages/clerk-js/src/core/resources/SignUp.tspackages/clerk-js/src/core/clerk.tspackages/react/src/isomorphicClerk.tspackages/types/src/web3.ts
.changeset/**
📄 CodeRabbit Inference Engine (.cursor/rules/monorepo.mdc)
Automated releases must use Changesets.
Files:
.changeset/silent-insects-cheat.md
🧬 Code Graph Analysis (5)
packages/clerk-js/src/core/resources/SignIn.ts (2)
packages/types/src/signIn.ts (1)
SignInResource(76-128)packages/clerk-js/src/utils/web3.ts (2)
getBaseAccountIdentifier(61-63)generateSignatureWithBaseAccount(82-84)
packages/clerk-js/src/utils/web3.ts (1)
packages/types/src/web3Wallet.ts (1)
GenerateSignatureParams(36-40)
packages/clerk-js/src/core/resources/SignUp.ts (2)
packages/types/src/signUp.ts (2)
SignUpAuthenticateWithWeb3Params(210-212)SignUpResource(50-120)packages/clerk-js/src/utils/web3.ts (2)
getBaseAccountIdentifier(61-63)generateSignatureWithBaseAccount(82-84)
packages/clerk-js/src/core/clerk.ts (2)
packages/types/src/clerk.ts (1)
AuthenticateWithCoinbaseWalletParams(2167-2173)packages/clerk-js/src/utils/web3.ts (3)
generateSignatureWithBaseAccount(82-84)generateSignatureWithCoinbaseWallet(74-76)generateSignatureWithOKXWallet(78-80)
packages/react/src/isomorphicClerk.ts (1)
packages/types/src/clerk.ts (1)
AuthenticateWithBaseAccountParams(2188-2194)
🪛 ESLint
packages/clerk-js/src/utils/web3.ts
[error] 108-108: 'e' is defined but never used.
(@typescript-eslint/no-unused-vars)
🪛 GitHub Actions: CI
packages/clerk-js/src/utils/web3.ts
[warning] 96-98: Module not found: Can't resolve '@base-org/account' in '/home/runner/_work/javascript/javascript/packages/clerk-js/src/utils' (import in web3.ts during build:bundle).
[error] 103-103: TS2307: Cannot find module '@base-org/account' or its corresponding type declarations.
⏰ 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: semgrep-cloud-platform/scan
- GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (9)
packages/types/src/web3.ts (1)
12-18: No action required:web3_base_account_signatureis already included in Web3Strategy
- Web3Strategy is defined as
export type Web3Strategy = \web3_${Web3Provider}_signature`;`- Web3Provider includes
export type BaseAccountWeb3Provider = 'base_account';
and is part of the union used in that template literal.- Therefore
'web3_base_account_signature'is implicitly part of Web3Strategy.packages/shared/src/web3.ts (1)
9-13: LGTM: provider entry added and order consistent with @clerk/typesProvider key, strategy, and display name look correct and align with the types registry. Good placement right after MetaMask.
packages/clerk-js/src/core/resources/SignIn.ts (1)
45-55: Imports for Base Account look correctNew web3 utils (
generateSignatureWithBaseAccount,getBaseAccountIdentifier) are imported consistently alongside existing providers.packages/clerk-js/src/core/clerk.ts (1)
103-124: Importing Base signature helper is fineThe added import for
generateSignatureWithBaseAccountis consistent with existing helpers.packages/clerk-js/src/core/resources/SignUp.ts (1)
29-39: Imports for Base Account utilities look goodConsistent import additions for
generateSignatureWithBaseAccountandgetBaseAccountIdentifier.packages/react/src/isomorphicClerk.ts (2)
15-55: Type surface updated to include Base Account paramsThe addition of
AuthenticateWithBaseAccountParamsto the types import is correct and enables proper typing downstream.
1354-1361: Isomorphic proxy for Base Account matches existing pattern (LGTM)Premount queuing + proxy call are implemented consistently with other auth methods.
packages/types/src/clerk.ts (2)
817-821: New Clerk API: authenticateWithBaseAccountAPI shape and return type match the existing wallet methods. Brief JSDoc is present. Looks good.
2188-2194: Params interface for Base Account is aligned with other providersThe params mirror the Coinbase/OKX parameter types. All good.
@clerk/agent-toolkit
@clerk/astro
@clerk/backend
@clerk/chrome-extension
@clerk/clerk-js
@clerk/dev-cli
@clerk/elements
@clerk/clerk-expo
@clerk/expo-passkeys
@clerk/express
@clerk/fastify
@clerk/localizations
@clerk/nextjs
@clerk/nuxt
@clerk/clerk-react
@clerk/react-router
@clerk/remix
@clerk/shared
@clerk/tanstack-react-start
@clerk/testing
@clerk/themes
@clerk/types
@clerk/upgrade
@clerk/vue
commit: |
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 (1)
packages/clerk-js/package.json (1)
66-66: Add/confirm tests for Base Account auth pathsIf not already in this PR, add tests covering:
- getBaseAccountIdentifier and generateSignatureWithBaseAccount happy/edge cases
- authenticateWithBaseAccount on Clerk, SignIn, SignUp, and IsomorphicClerk flows (success, user cancel, provider unavailable)
- Strategy wiring to web3_base_account_signature in shared provider list
This helps prevent regressions across sign-in/sign-up surfaces.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
⛔ Files ignored due to path filters (1)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yaml
📒 Files selected for processing (2)
packages/clerk-js/package.json(1 hunks)packages/clerk-js/src/core/clerk.ts(4 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- packages/clerk-js/src/core/clerk.ts
🧰 Additional context used
📓 Path-based instructions (3)
**/*.{js,jsx,ts,tsx,json,css,scss,md,yaml,yml}
📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)
Use Prettier for consistent code formatting
Files:
packages/clerk-js/package.json
packages/*/package.json
📄 CodeRabbit Inference Engine (.cursor/rules/global.mdc)
All publishable packages should be placed under the packages/ directory
packages/*/package.json: All publishable packages must be located in the 'packages/' directory.
All packages must be published under the @clerk namespace on npm.
Semantic versioning must be used across all packages.
Files:
packages/clerk-js/package.json
**/*
⚙️ CodeRabbit Configuration File
If there are no tests added or modified as part of the PR, please suggest that tests be added to cover the changes.
Files:
packages/clerk-js/package.json
⏰ 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). (6)
- GitHub Check: Formatting | Dedupe | Changeset
- GitHub Check: Build Packages
- GitHub Check: Analyze (javascript-typescript)
- GitHub Check: semgrep/ci
- GitHub Check: semgrep-cloud-platform/scan
- GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (2)
packages/clerk-js/package.json (2)
66-66: Dependency addition looks correct and consistent with existing Web3 depsPinning "@base-org/account" to 2.0.1 mirrors the exact-pin approach used for "@coinbase/wallet-sdk" and aligns with the PR’s Base Account support. Good placement under runtime dependencies.
66-66: Dependency health check: @base-org/account@2.0.1
- License: Apache-2.0 (MIT-compatible)
- Peer dependencies: none
- Vulnerabilities (OSV): none found
- Module format: ESM only (pkg.json
"type":"module"); CJS entries declared but Node will treat.jsas ESM- Browser support:
browserfield points todist/base-account.min.jsfor script-tag usage- Registry metadata: 371 files, unpacked size ~7.39 MB (no
dist.sizereported)Please run local bundle-impact checks before merge:
• pnpm --filter @clerk/clerk-js bundlewatch
• pnpm --filter @clerk/clerk-js build:stats (inspect stats.json)
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: 4
♻️ Duplicate comments (1)
packages/clerk-js/src/utils/web3.ts (1)
101-111: Add RHC/unsupported env guard and surface a dev-friendly warning on import failureCoinbase branch guards
__BUILD_DISABLE_RHC__and emits an environment warning. Mirror that for Base Wallet to avoid SSR/RHC pitfalls and help developers debug missing SDK installs. Also consider a dev-only warning in the catch.Apply this diff:
if (provider === 'base_wallet') { - try { + if (__BUILD_DISABLE_RHC__) { + clerkUnsupportedEnvironmentWarning('Base Wallet'); + return null; + } + try { const { createBaseAccountSDK } = await import('@base-org/account'); const sdk = createBaseAccountSDK({ appName: typeof document !== 'undefined' ? document.title || 'Clerk' : 'Clerk', }); return sdk.getProvider(); } catch { + // Optionally log a dev-friendly warning (guard with your internal dev flag if available) + // console.warn('[Clerk] Failed to initialize Base Account SDK. Is @base-org/account installed?'); return null; } }
🧹 Nitpick comments (1)
packages/types/src/clerk.ts (1)
2188-2195: Add JSDoc for new public params interfaceAll public APIs and their params should be documented. Add a short JSDoc block to mirror the other wallet param interfaces.
Apply this diff:
+/** + * Parameters for {@link Clerk.authenticateWithBaseWallet}. + * Mirrors {@link AuthenticateWithCoinbaseWalletParams}. + */ export interface AuthenticateWithBaseWalletParams { customNavigate?: (to: string) => Promise<unknown>; redirectUrl?: string; signUpContinueUrl?: string; unsafeMetadata?: SignUpUnsafeMetadata; legalAccepted?: boolean; }
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (10)
packages/clerk-js/src/core/clerk.ts(4 hunks)packages/clerk-js/src/core/resources/SignIn.ts(3 hunks)packages/clerk-js/src/core/resources/SignUp.ts(2 hunks)packages/clerk-js/src/utils/web3.ts(3 hunks)packages/react/src/isomorphicClerk.ts(2 hunks)packages/shared/src/web3.ts(1 hunks)packages/types/src/clerk.ts(2 hunks)packages/types/src/signIn.ts(1 hunks)packages/types/src/signUp.ts(1 hunks)packages/types/src/web3.ts(2 hunks)
🚧 Files skipped from review as they are similar to previous changes (6)
- packages/types/src/signIn.ts
- packages/react/src/isomorphicClerk.ts
- packages/types/src/signUp.ts
- packages/shared/src/web3.ts
- packages/clerk-js/src/core/resources/SignIn.ts
- packages/clerk-js/src/core/clerk.ts
🧰 Additional context used
📓 Path-based instructions (7)
**/*.{js,jsx,ts,tsx}
📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)
**/*.{js,jsx,ts,tsx}: All code must pass ESLint checks with the project's configuration
Follow established naming conventions (PascalCase for components, camelCase for variables)
Maintain comprehensive JSDoc comments for public APIs
Use dynamic imports for optional features
All public APIs must be documented with JSDoc
Provide meaningful error messages to developers
Include error recovery suggestions where applicable
Log errors appropriately for debugging
Lazy load components and features when possible
Implement proper caching strategies
Use efficient data structures and algorithms
Profile and optimize critical paths
Validate all inputs and sanitize outputs
Implement proper logging with different levels
Files:
packages/clerk-js/src/core/resources/SignUp.tspackages/types/src/clerk.tspackages/types/src/web3.tspackages/clerk-js/src/utils/web3.ts
**/*.{js,jsx,ts,tsx,json,css,scss,md,yaml,yml}
📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)
Use Prettier for consistent code formatting
Files:
packages/clerk-js/src/core/resources/SignUp.tspackages/types/src/clerk.tspackages/types/src/web3.tspackages/clerk-js/src/utils/web3.ts
packages/**/*.{ts,tsx}
📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)
TypeScript is required for all packages
Files:
packages/clerk-js/src/core/resources/SignUp.tspackages/types/src/clerk.tspackages/types/src/web3.tspackages/clerk-js/src/utils/web3.ts
packages/**/*.{ts,tsx,d.ts}
📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)
Packages should export TypeScript types alongside runtime code
Files:
packages/clerk-js/src/core/resources/SignUp.tspackages/types/src/clerk.tspackages/types/src/web3.tspackages/clerk-js/src/utils/web3.ts
**/*.{ts,tsx}
📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)
Use proper TypeScript error types
**/*.{ts,tsx}: Always define explicit return types for functions, especially public APIs
Use proper type annotations for variables and parameters where inference isn't clear
Avoidanytype - preferunknownwhen type is uncertain, then narrow with type guards
Useinterfacefor object shapes that might be extended
Usetypefor unions, primitives, and computed types
Preferreadonlyproperties for immutable data structures
Useprivatefor internal implementation details
Useprotectedfor inheritance hierarchies
Usepublicexplicitly for clarity in public APIs
Preferreadonlyfor properties that shouldn't change after construction
Prefer composition and interfaces over deep inheritance chains
Use mixins for shared behavior across unrelated classes
Implement dependency injection for loose coupling
Let TypeScript infer when types are obvious
Useconst assertionsfor literal types:as const
Usesatisfiesoperator for type checking without widening
Use mapped types for transforming object types
Use conditional types for type-level logic
Leverage template literal types for string manipulation
Use ES6 imports/exports consistently
Use default exports sparingly, prefer named exports
Use type-only imports:import type { ... } from ...
Noanytypes without justification
Proper error handling with typed errors
Consistent use ofreadonlyfor immutable data
Proper generic constraints
No unused type parameters
Proper use of utility types instead of manual type construction
Type-only imports where possible
Proper tree-shaking friendly exports
No circular dependencies
Efficient type computations (avoid deep recursion)
Files:
packages/clerk-js/src/core/resources/SignUp.tspackages/types/src/clerk.tspackages/types/src/web3.tspackages/clerk-js/src/utils/web3.ts
**/*.{js,ts,tsx,jsx}
📄 CodeRabbit Inference Engine (.cursor/rules/monorepo.mdc)
Support multiple Clerk environment variables (CLERK_, NEXT_PUBLIC_CLERK_, etc.) for configuration.
Files:
packages/clerk-js/src/core/resources/SignUp.tspackages/types/src/clerk.tspackages/types/src/web3.tspackages/clerk-js/src/utils/web3.ts
**/*
⚙️ CodeRabbit Configuration File
If there are no tests added or modified as part of the PR, please suggest that tests be added to cover the changes.
Files:
packages/clerk-js/src/core/resources/SignUp.tspackages/types/src/clerk.tspackages/types/src/web3.tspackages/clerk-js/src/utils/web3.ts
🧬 Code Graph Analysis (2)
packages/clerk-js/src/core/resources/SignUp.ts (2)
packages/types/src/signUp.ts (2)
SignUpAuthenticateWithWeb3Params(210-212)SignUpResource(50-120)packages/clerk-js/src/utils/web3.ts (2)
getBaseWalletIdentifier(61-63)generateSignatureWithCoinbaseWallet(74-76)
packages/clerk-js/src/utils/web3.ts (1)
packages/types/src/web3Wallet.ts (1)
GenerateSignatureParams(36-40)
⏰ 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). (4)
- GitHub Check: Build Packages
- GitHub Check: Formatting | Dedupe | Changeset
- GitHub Check: semgrep/ci
- GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (3)
packages/clerk-js/src/utils/web3.ts (1)
61-63: LGTM: Identifier helper for Base Wallet mirrors existing patternThis wrapper correctly plugs Base Wallet into the generic getWeb3Identifier flow.
packages/types/src/clerk.ts (1)
817-821: LGTM: Public Clerk API gains Base Wallet methodAPI shape and JSDoc align with existing Metamask/Coinbase/OKX entries.
packages/types/src/web3.ts (1)
31-35: LGTM: Base Wallet provider & strategy union verified
- Confirmed
base_walletis included in theWeb3Providerunion inpackages/types/src/web3.ts- The template-literal
Web3Strategy = \web3_${Web3Provider}_signature`automatically coversweb3_base_wallet_signature`- Shared
WEB3_PROVIDERSinpackages/shared/src/web3.tsincludes the new Base Wallet entryNo further changes needed.
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 (3)
packages/elements/src/react/hooks/use-third-party-provider.hook.ts (3)
79-95: Reduce duplication: map Web3 providers to strategies instead of chained conditionalsConsolidating the provider→strategy mapping reduces chance of omissions when adding new wallets and keeps this logic DRY.
Apply this diff to replace the four Web3-specific ifs with a single mapping:
- if (provider === 'base_wallet') { - return ref.send({ type: 'AUTHENTICATE.WEB3', strategy: 'web3_base_wallet_signature' }); - } - - if (provider === 'metamask') { - return ref.send({ type: 'AUTHENTICATE.WEB3', strategy: 'web3_metamask_signature' }); - } - - if (provider === 'coinbase_wallet') { - return ref.send({ type: 'AUTHENTICATE.WEB3', strategy: 'web3_coinbase_wallet_signature' }); - } - - if (provider === 'okx_wallet') { - return ref.send({ type: 'AUTHENTICATE.WEB3', strategy: 'web3_okx_wallet_signature' }); - } + const web3StrategyByProvider = { + metamask: 'web3_metamask_signature', + coinbase_wallet: 'web3_coinbase_wallet_signature', + okx_wallet: 'web3_okx_wallet_signature', + base_wallet: 'web3_base_wallet_signature', + } as const satisfies Record<Web3Provider, string>; + + const web3Strategy = web3StrategyByProvider[provider as Web3Provider]; + if (web3Strategy) { + return ref.send({ type: 'AUTHENTICATE.WEB3', strategy: web3Strategy }); + }
100-105: Fix dashboard link for all Web3 providers (including Base Wallet)The error message links to the Web3 dashboard section only for MetaMask. Base Wallet (and other Web3 wallets) should also route to /web3.
Apply this diff to generalize the path:
- const dashboardPath = `https://dashboard.clerk.com/last-active?path=/user-authentication/${provider === 'metamask' ? 'web3' : 'social-connections'}`; + const isWeb3Provider = + provider === 'metamask' || + provider === 'coinbase_wallet' || + provider === 'okx_wallet' || + provider === 'base_wallet'; + const dashboardPath = `https://dashboard.clerk.com/last-active?path=/user-authentication/${isWeb3Provider ? 'web3' : 'social-connections'}`;
63-98: Add tests for Base Wallet flow through this hookPlease add unit/integration tests to cover:
- authenticate() dispatch for provider === 'base_wallet' (AUTHENTICATE.WEB3 with web3_base_wallet_signature)
- Error path when Base Wallet is disabled (throws with correct dashboard link)
I can scaffold tests for the hook (using react-testing-library + xstate actor mocks). Want me to open a follow-up PR with test coverage?
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (1)
packages/elements/src/react/hooks/use-third-party-provider.hook.ts(1 hunks)
🧰 Additional context used
📓 Path-based instructions (7)
**/*.{js,jsx,ts,tsx}
📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)
**/*.{js,jsx,ts,tsx}: All code must pass ESLint checks with the project's configuration
Follow established naming conventions (PascalCase for components, camelCase for variables)
Maintain comprehensive JSDoc comments for public APIs
Use dynamic imports for optional features
All public APIs must be documented with JSDoc
Provide meaningful error messages to developers
Include error recovery suggestions where applicable
Log errors appropriately for debugging
Lazy load components and features when possible
Implement proper caching strategies
Use efficient data structures and algorithms
Profile and optimize critical paths
Validate all inputs and sanitize outputs
Implement proper logging with different levels
Files:
packages/elements/src/react/hooks/use-third-party-provider.hook.ts
**/*.{js,jsx,ts,tsx,json,css,scss,md,yaml,yml}
📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)
Use Prettier for consistent code formatting
Files:
packages/elements/src/react/hooks/use-third-party-provider.hook.ts
packages/**/*.{ts,tsx}
📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)
TypeScript is required for all packages
Files:
packages/elements/src/react/hooks/use-third-party-provider.hook.ts
packages/**/*.{ts,tsx,d.ts}
📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)
Packages should export TypeScript types alongside runtime code
Files:
packages/elements/src/react/hooks/use-third-party-provider.hook.ts
**/*.{ts,tsx}
📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)
Use proper TypeScript error types
**/*.{ts,tsx}: Always define explicit return types for functions, especially public APIs
Use proper type annotations for variables and parameters where inference isn't clear
Avoidanytype - preferunknownwhen type is uncertain, then narrow with type guards
Useinterfacefor object shapes that might be extended
Usetypefor unions, primitives, and computed types
Preferreadonlyproperties for immutable data structures
Useprivatefor internal implementation details
Useprotectedfor inheritance hierarchies
Usepublicexplicitly for clarity in public APIs
Preferreadonlyfor properties that shouldn't change after construction
Prefer composition and interfaces over deep inheritance chains
Use mixins for shared behavior across unrelated classes
Implement dependency injection for loose coupling
Let TypeScript infer when types are obvious
Useconst assertionsfor literal types:as const
Usesatisfiesoperator for type checking without widening
Use mapped types for transforming object types
Use conditional types for type-level logic
Leverage template literal types for string manipulation
Use ES6 imports/exports consistently
Use default exports sparingly, prefer named exports
Use type-only imports:import type { ... } from ...
Noanytypes without justification
Proper error handling with typed errors
Consistent use ofreadonlyfor immutable data
Proper generic constraints
No unused type parameters
Proper use of utility types instead of manual type construction
Type-only imports where possible
Proper tree-shaking friendly exports
No circular dependencies
Efficient type computations (avoid deep recursion)
Files:
packages/elements/src/react/hooks/use-third-party-provider.hook.ts
**/*.{js,ts,tsx,jsx}
📄 CodeRabbit Inference Engine (.cursor/rules/monorepo.mdc)
Support multiple Clerk environment variables (CLERK_, NEXT_PUBLIC_CLERK_, etc.) for configuration.
Files:
packages/elements/src/react/hooks/use-third-party-provider.hook.ts
**/*
⚙️ CodeRabbit Configuration File
If there are no tests added or modified as part of the PR, please suggest that tests be added to cover the changes.
Files:
packages/elements/src/react/hooks/use-third-party-provider.hook.ts
⏰ 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). (4)
- GitHub Check: Formatting | Dedupe | Changeset
- GitHub Check: Build Packages
- GitHub Check: semgrep/ci
- GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (1)
packages/elements/src/react/hooks/use-third-party-provider.hook.ts (1)
79-81: Verified: Base Wallet Web3 strategy fully integratedAll checks confirm that the new
base_walletbranch is correctly wired:
WEB3_PROVIDERSentries in bothpackages/types/src/web3.tsandpackages/shared/src/web3.tsincludeprovider: 'base_wallet'withstrategy: 'web3_base_wallet_signature'.providerToDisplayData(fromthird-party-strategies.ts) aggregatesWEB3_PROVIDERS, soproviderToDisplayData['base_wallet']is defined.Web3ProviderandWeb3Strategytypes inpackages/types/srcincludeBaseWalletWeb3Provider('base_wallet') and therefore the strategy templateweb3_${Web3Provider}_signaturecoversweb3_base_wallet_signature.- Router types (
BaseRouterRedirectWeb3Event) and both Sign-In/Sign-Up XState machines accept the'AUTHENTICATE.WEB3'event with our strategy.All dependencies, types, registries, and state transitions are in place.
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.
Nice! Just one simple comment regarding remotely hosted code.
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 (2)
packages/clerk-js/rspack.config.js (2)
104-110: Isolate @base-org/account into its own async chunk (nice). Consider grouping its deps to avoid extra network hops.The dedicated cacheGroup with higher priority ensures Base Account code doesn’t bleed into vendors. To further reduce additional async vendor requests, consider capturing the dependency subtree of @base-org/account into the same chunk (when those deps aren’t shared elsewhere) by matching on the issuer chain.
Apply this if you want to co-locate its non-shared deps with the base-account chunk:
- baseAccountVendor: { - test: /[\\/]node_modules[\\/](@base-org\/account)[\\/]/, - name: 'base-account', - chunks: 'async', - priority: 50, - enforce: true, - }, + baseAccountVendor: { + // Group @base-org/account and its dependency subtree into one async chunk + test: module => { + const re = /[\\/]node_modules[\\/]@base-org[\\/]account[\\/]/; + const res = module.resource || ''; + if (re.test(res)) return true; + // Walk issuer chain to include modules whose issuer is @base-org/account + let issuer = module.issuer; + while (issuer) { + const issuerRes = issuer.resource || ''; + if (re.test(issuerRes)) return true; + issuer = issuer.issuer; + } + return false; + }, + name: 'base-account', + chunks: 'async', + priority: 50, + enforce: true, + },Note: If any of those deps are also used by initial chunks, rspack will prefer hoisting to shared vendors; this keeps duplication low while still attempting to co-locate when possible.
129-129: Confirm intention: ui-common limited to initial chunksSwitching ui-common to chunks: 'initial' can reduce the risk of async-only code leaking into the common chunk, but may also reduce cross-chunk reuse and slightly increase async payload duplication. If unintentional, consider using 'all' here.
If broader sharing was intended:
- chunks: 'initial', + chunks: 'all',
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (3)
packages/clerk-js/bundlewatch.config.json(1 hunks)packages/clerk-js/rspack.config.js(2 hunks)packages/clerk-js/src/utils/web3.ts(3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- packages/clerk-js/src/utils/web3.ts
🧰 Additional context used
📓 Path-based instructions (4)
**/*.{js,jsx,ts,tsx,json,css,scss,md,yaml,yml}
📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)
Use Prettier for consistent code formatting
Files:
packages/clerk-js/bundlewatch.config.jsonpackages/clerk-js/rspack.config.js
**/*
⚙️ CodeRabbit Configuration File
If there are no tests added or modified as part of the PR, please suggest that tests be added to cover the changes.
Files:
packages/clerk-js/bundlewatch.config.jsonpackages/clerk-js/rspack.config.js
**/*.{js,jsx,ts,tsx}
📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)
**/*.{js,jsx,ts,tsx}: All code must pass ESLint checks with the project's configuration
Follow established naming conventions (PascalCase for components, camelCase for variables)
Maintain comprehensive JSDoc comments for public APIs
Use dynamic imports for optional features
All public APIs must be documented with JSDoc
Provide meaningful error messages to developers
Include error recovery suggestions where applicable
Log errors appropriately for debugging
Lazy load components and features when possible
Implement proper caching strategies
Use efficient data structures and algorithms
Profile and optimize critical paths
Validate all inputs and sanitize outputs
Implement proper logging with different levels
Files:
packages/clerk-js/rspack.config.js
**/*.{js,ts,tsx,jsx}
📄 CodeRabbit Inference Engine (.cursor/rules/monorepo.mdc)
Support multiple Clerk environment variables (CLERK_, NEXT_PUBLIC_CLERK_, etc.) for configuration.
Files:
packages/clerk-js/rspack.config.js
⏰ 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). (6)
- GitHub Check: Build Packages
- GitHub Check: Formatting | Dedupe | Changeset
- GitHub Check: semgrep/ci
- GitHub Check: Analyze (javascript-typescript)
- GitHub Check: semgrep-cloud-platform/scan
- GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (2)
packages/clerk-js/bundlewatch.config.json (1)
11-11: Verify base-account bundlewatch entryBefore approving, please perform the following checks once your CI artifacts are available:
Confirm the emitted chunk filenames under
packages/clerk-js/distmatch the globbase-account*.js(rspack usesname: 'base-account'plus any hash or variant suffix).Measure the actual size of the async “base-account” chunk and adjust the
"maxSize": "45KB"threshold accordingly.Ensure the cache group in
packages/clerk-js/rspack.config.jsis named exactly'base-account'and targets only async chunks:baseAccountVendor: { test: /[\\/]node_modules[\\/]@base-org\/account[\\/]/, name: 'base-account', chunks: 'async', priority: 50, },Verify there are no static imports or CommonJS requires of
@base-org/account(it must be loaded dynamically):rg -n -C2 "import\s+.*from\s+['\"]@base-org/account['\"]" packages/clerk-js rg -n -C2 "require\(['\"]@base-org/account['\"]\)" packages/clerk-js rg -n -C2 "import\(['\"]@base-org/account" packages/clerk-jsOnce you’ve validated filenames, import patterns, and size, please update the budget if needed and mark this ready.
packages/clerk-js/rspack.config.js (1)
134-139: Exclude @base-org/account from defaultVendors (good).Guarding on module.resource and excluding @base-org/account avoids it being folded into vendors, letting the dedicated cacheGroup own it. Looks correct.
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
♻️ Duplicate comments (2)
packages/clerk-js/src/utils/web3.ts (2)
82-84: Public API: add JSDoc, export type, and ensure the symbol is re-exported from the utils barrel
- Add JSDoc for this new export.
- Consider exporting the
GenerateSignatureParamstype since it’s part of the public function signature.- Ensure
generateSignatureWithBase(andgetBaseIdentifier) are re-exported frompackages/clerk-js/src/utils/index.tsto avoid downstream import errors.JSDoc to add (outside the selected lines):
/** * Generate a personal_sign signature using the Base provider. * Returns an empty string if the provider is unavailable. */ export async function generateSignatureWithBase(params: GenerateSignatureParams): Promise<string> { // ... }Export the param type (outside the selected lines):
export type GenerateSignatureParams = { identifier: string; nonce: string; };Re-export from the utils barrel (outside this file):
// packages/clerk-js/src/utils/index.ts export { getBaseIdentifier, generateSignatureWithBase } from './web3';Run this script to verify re-exports:
#!/usr/bin/env bash set -euo pipefail echo "Finding utils barrel(s) and checking exports..." fd -t f -e ts 'index*' packages/clerk-js/src/utils | while read -r f; do echo "— $f" rg -nP '\bexport\b.+\bgetBaseIdentifier\b' "$f" || true rg -nP '\bexport\b.+\bgenerateSignatureWithBase\b' "$f" || true done
101-116: Base provider dynamic import is correctly gated; recommend caching, resilient import shape, and a dev warning on failureGood job honoring the No RHC/Chrome Extension build guard with
__BUILD_DISABLE_RHC__. That addresses prior concerns about shipping this path in restricted builds. Consider:
- Cache the Base provider to avoid re-instantiating the SDK on repeated calls.
- Be resilient to different module export shapes (named vs default).
- Emit a dev-time warning on import/init failure to aid setup/debugging.
Apply within this hunk:
- if (provider === 'base') { + if (provider === 'base') { if (__BUILD_DISABLE_RHC__) { clerkUnsupportedEnvironmentWarning('Base'); return null; } - try { - const createBaseAccountSDK = await import('@base-org/account').then(mod => mod.createBaseAccountSDK); - const sdk = createBaseAccountSDK({ - appName: typeof document !== 'undefined' ? document.title || 'Clerk' : 'Clerk', - }); - return sdk.getProvider(); - } catch { - return null; - } + // lazy, cached initialization + try { + if (!baseProviderPromise) { + baseProviderPromise = (async () => { + const mod: any = await import('@base-org/account'); + const createBaseAccountSDK = + mod?.createBaseAccountSDK ?? mod?.default?.createBaseAccountSDK ?? mod?.default; + if (typeof createBaseAccountSDK !== 'function') { + if (process.env.NODE_ENV !== 'production') { + console.warn('[Clerk] @base-org/account: missing createBaseAccountSDK export. Check installed version.'); + } + return null; + } + const sdk = createBaseAccountSDK({ + appName: typeof document !== 'undefined' ? document.title || 'Clerk' : 'Clerk', + }); + return sdk.getProvider(); + })(); + } + return await baseProviderPromise; + } catch { + if (process.env.NODE_ENV !== 'production') { + console.warn('[Clerk] Failed to initialize Base Account SDK. Is @base-org/account installed?'); + } + return null; + } }Add these (outside the selected lines) near the top of the module to type and cache the provider:
type EIP1193Provider = { request(args: { method: string; params?: unknown[] }): Promise<unknown>; }; let baseProviderPromise: Promise<EIP1193Provider | null> | undefined;Verify dependency and type shim exist:
#!/usr/bin/env bash set -euo pipefail echo "Checking for @base-org/account dependency..." rg -n --glob 'packages/clerk-js/package.json' '"@base-org/account"\s*:' || { echo "Missing @base-org/account in packages/clerk-js/package.json"; exit 1; } echo echo "Checking for type shim if the package ships no types..." fd -t f -e d.ts packages/clerk-js | xargs rg -nP "declare\s+module\s+['\"]@base-org/account['\"]" || echo "No local shim found (ok if upstream provides types)"
🧹 Nitpick comments (3)
packages/clerk-js/src/utils/web3.ts (3)
23-25: Remove the ts-ignore and narrow the provider response with a type guardAvoid suppressing type errors here. Narrow the
eth_requestAccountsresult at runtime to astring[]and return the first address if present.Apply within this hunk:
- const identifiers = await ethereum.request({ method: 'eth_requestAccounts' }); - // @ts-ignore -- Provider SDKs may return unknown shape; use first address if present - return (identifiers && identifiers[0]) || ''; + const identifiers = (await ethereum.request({ method: 'eth_requestAccounts' })) as unknown; + if (isStringArray(identifiers) && identifiers.length > 0) { + return identifiers[0]; + } + return '';Add this helper (outside the selected lines) to the module:
function isStringArray(value: unknown): value is string[] { return Array.isArray(value) && value.every(v => typeof v === 'string'); }
61-63: Public API: add JSDoc and consider naming alignment with other providersTwo tweaks:
- Add JSDoc to comply with our guidelines for public APIs.
- Consider aligning the name with other helpers (e.g.,
getCoinbaseWalletIdentifier) by either renaming togetBaseWalletIdentifieror exporting an alias to keep the surface consistent. If you keepgetBaseIdentifier, exporting an alias avoids churn for future consumers.JSDoc to add (outside the selected lines):
/** * Resolve the active Base account address by requesting accounts access from the Base provider. * Returns an empty string if the provider is unavailable or access is denied. */ export async function getBaseIdentifier(): Promise<string> { // ... }Optional alias (outside this file’s hunk):
export async function getBaseWalletIdentifier(): Promise<string> { return getBaseIdentifier(); }
118-118: Normalize provider fallback to return null consistently
getInjectedWeb3Providers().get(provider)returnsEIP1193Provider | undefined. Elsewhere in this function you returnnullfor “not available”. Normalize the return for consistency and easier downstream checks.- return getInjectedWeb3Providers().get(provider); + return getInjectedWeb3Providers().get(provider) ?? null;
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (2)
packages/clerk-js/src/utils/web3.ts(4 hunks)packages/elements/src/internals/machines/sign-in/start.machine.ts(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- packages/elements/src/internals/machines/sign-in/start.machine.ts
🧰 Additional context used
📓 Path-based instructions (6)
**/*.{js,jsx,ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
**/*.{js,jsx,ts,tsx}: All code must pass ESLint checks with the project's configuration
Follow established naming conventions (PascalCase for components, camelCase for variables)
Maintain comprehensive JSDoc comments for public APIs
Use dynamic imports for optional features
All public APIs must be documented with JSDoc
Provide meaningful error messages to developers
Include error recovery suggestions where applicable
Log errors appropriately for debugging
Lazy load components and features when possible
Implement proper caching strategies
Use efficient data structures and algorithms
Profile and optimize critical paths
Validate all inputs and sanitize outputs
Implement proper logging with different levels
Files:
packages/clerk-js/src/utils/web3.ts
**/*.{js,jsx,ts,tsx,json,css,scss,md,yaml,yml}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
Use Prettier for consistent code formatting
Files:
packages/clerk-js/src/utils/web3.ts
packages/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
TypeScript is required for all packages
Files:
packages/clerk-js/src/utils/web3.ts
packages/**/*.{ts,tsx,d.ts}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
Packages should export TypeScript types alongside runtime code
Files:
packages/clerk-js/src/utils/web3.ts
**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
Use proper TypeScript error types
**/*.{ts,tsx}: Always define explicit return types for functions, especially public APIs
Use proper type annotations for variables and parameters where inference isn't clear
Avoidanytype - preferunknownwhen type is uncertain, then narrow with type guards
Useinterfacefor object shapes that might be extended
Usetypefor unions, primitives, and computed types
Preferreadonlyproperties for immutable data structures
Useprivatefor internal implementation details
Useprotectedfor inheritance hierarchies
Usepublicexplicitly for clarity in public APIs
Preferreadonlyfor properties that shouldn't change after construction
Prefer composition and interfaces over deep inheritance chains
Use mixins for shared behavior across unrelated classes
Implement dependency injection for loose coupling
Let TypeScript infer when types are obvious
Useconst assertionsfor literal types:as const
Usesatisfiesoperator for type checking without widening
Use mapped types for transforming object types
Use conditional types for type-level logic
Leverage template literal types for string manipulation
Use ES6 imports/exports consistently
Use default exports sparingly, prefer named exports
Use type-only imports:import type { ... } from ...
Noanytypes without justification
Proper error handling with typed errors
Consistent use ofreadonlyfor immutable data
Proper generic constraints
No unused type parameters
Proper use of utility types instead of manual type construction
Type-only imports where possible
Proper tree-shaking friendly exports
No circular dependencies
Efficient type computations (avoid deep recursion)
Files:
packages/clerk-js/src/utils/web3.ts
**/*.{js,ts,tsx,jsx}
📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)
Support multiple Clerk environment variables (CLERK_, NEXT_PUBLIC_CLERK_, etc.) for configuration.
Files:
packages/clerk-js/src/utils/web3.ts
⏰ 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: Build Packages
- GitHub Check: semgrep/ci
- GitHub Check: Analyze (javascript-typescript)
- GitHub Check: semgrep-cloud-platform/scan
- GitHub Check: semgrep-cloud-platform/scan
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
♻️ Duplicate comments (1)
packages/clerk-js/bundlewatch.config.json (1)
2-34: Add a Base async-chunk budget and calibrate to real size (+10–15% headroom).This PR introduces Base auth, but there’s no bundlewatch entry for the Base SDK async chunk (e.g., base-account*.js). Without it, size regressions for the new provider won’t be tracked. Also ensure the emitted chunk name matches the pattern you add.
Suggested change (temporary cap; update after a local build):
{ "path": "./dist/coinbase*.js", "maxSize": "38KB" }, + { "path": "./dist/base-account*.js", "maxSize": "45KB" },Follow-up:
- Rebuild locally, measure the emitted base-account*.js, and set maxSize to current size + ~10–15% headroom.
- Verify your dynamic import/rs[pack|webpack] config names the chunk to match ./dist/base-account*.js, otherwise bundlewatch won’t catch it.
Run this to verify chunk naming and derive a data-driven budget:
#!/bin/bash set -euo pipefail echo "1) Check for dynamic import and chunk naming hints" rg -nP -C2 'import\\s*\\(.*@base-org/account' --glob '**/*.{js,ts,tsx}' || true rg -nP -C2 'webpackChunkName.*base-account' --glob '**/*.{js,ts,tsx}' || true rg -nP -C2 '(split|chunk).*base-account' --glob '**/*rspack*.{js,ts,tsx}' || true echo -e "\n2) Build and measure emitted Base chunk" pnpm -w build >/dev/null 2>&1 || echo "Build failed or unavailable; run locally." node - <<'NODE' || true const fs=require('fs'), p='packages/clerk-js/dist'; if(!fs.existsSync(p)){ console.error('No dist at',p); process.exit(0); } const files=fs.readdirSync(p).filter(f=>/^base-account.*\.js$/.test(f)); if(files.length===0){ console.error('No base-account*.js found. Is the chunk named differently or inlined?'); process.exit(0); } const kb=b=>Math.round((b/1024)*10)/10; let max=0; for(const f of files){ const s=fs.statSync(p+'/'+f).size; max=Math.max(max,s); console.log(f, kb(s)+'KB'); } console.log('Suggested maxSize:', Math.ceil((max/1024)*1.10)+'KB'); // +10% headroom NODE
🧹 Nitpick comments (2)
packages/clerk-js/bundlewatch.config.json (2)
3-3: 818KB ceiling for clerk.js is a big jump—validate it’s not masking accidental inlining.Large bumps on the root bundle can hide misconfigured code-splitting. Confirm that the Base SDK is lazy-loaded into a separate async chunk (not bundled into clerk.js), and then set this threshold to the measured size + modest headroom instead of a blanket increase.
To verify:
- Ensure the Base import is truly dynamic and that a base-account*.js chunk is emitted alongside clerk.js.
- If clerk.js grew primarily due to Base, re-check splitChunks/cacheGroup to keep provider SDKs in their own lazy chunks and keep clerk.js stable.
9-9: Raising the global vendors.js budget can mask unrelated growth—prefer targeted budgets.*A higher umbrella limit for vendors*.js makes regressions harder to spot. Keep vendors tight and add a specific entry for the Base SDK (and, if needed, a dedicated vendors chunk for it) rather than loosening the entire vendor ceiling.
Action items:
- Revert/trim vendors*.js headroom unless you have measured growth that can’t be isolated.
- If rspack creates a dedicated vendor group for Base, track it explicitly (e.g., base-account-vendors*.js) with its own budget instead of broadening vendors*.js.
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (2)
packages/clerk-js/bundlewatch.config.json(1 hunks)packages/clerk-js/rspack.config.js(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- packages/clerk-js/rspack.config.js
🧰 Additional context used
📓 Path-based instructions (1)
**/*.{js,jsx,ts,tsx,json,css,scss,md,yaml,yml}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
Use Prettier for consistent code formatting
Files:
packages/clerk-js/bundlewatch.config.json
⏰ 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: Build Packages
- GitHub Check: semgrep/ci
- GitHub Check: semgrep-cloud-platform/scan
- GitHub Check: Analyze (javascript-typescript)
- GitHub Check: semgrep-cloud-platform/scan
| default: | ||
| generateSignature = generateSignatureWithOKXWallet; | ||
| break; |
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.
I don't think we should be falling back to OKXWallet here, but that is the pre-existing functionality
| case 'web3_metamask_signature': | ||
| config = { web3WalletId: factor.web3WalletId } as Web3SignatureConfig; | ||
| break; | ||
| case 'web3_base_signature': |
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.
Did a small refactor here to remove the copy-pasta
| return sdk.getProvider(); | ||
| } | ||
| if (provider === 'base') { | ||
| if (__BUILD_DISABLE_RHC__) { |
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.
Cannot include this in the no-remote-hosted-code builds
| { | ||
| "files": [ | ||
| { "path": "./dist/clerk.js", "maxSize": "631KB" }, | ||
| { "path": "./dist/clerk.js", "maxSize": "818KB" }, |
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.
Yep. @base-org/account is pretty massive
| chunks: 'all', | ||
| }, | ||
| baseAccountSDKVendor: { | ||
| test: /[\\/]node_modules[\\/](@base-org\/account|@noble\/curves|abitype|ox|preact|eventemitter3|viem|zustand)[\\/]/, |
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.
This is needed to avoid bundling @base-org/account transitive dependencies in our main vendor chunks
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.
The no-RHC build is 👍
| { "path": "./dist/ui-common*.js", "maxSize": "117.1KB" }, | ||
| { "path": "./dist/ui-common*.legacy.*.js", "maxSize": "118KB" }, | ||
| { "path": "./dist/vendors*.js", "maxSize": "43.78KB" }, | ||
| { "path": "./dist/vendors*.js", "maxSize": "45KB" }, |
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.
@jacekradko Is this expected ? Maybe something belongs to baseAccountSDKVendor ?
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.
I can dig into it, but yeah it's gotta be another transitive dependency of a transitive dependency type of thing 😂
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 (1)
packages/clerk-js/vitest.config.mts (1)
26-31: Add a TS global declaration for the new build flagTo avoid implicit-any globals in TS-aware editors/builds, declare the symbol alongside the other build flags.
Create or extend your build-flags declarations (e.g., packages/clerk-js/src/types/build-flags.d.ts):
declare const __BUILD_DISABLE_RHC__: boolean;
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (2)
packages/clerk-js/src/utils/web3.ts(4 hunks)packages/clerk-js/vitest.config.mts(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- packages/clerk-js/src/utils/web3.ts
⏰ 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: Build Packages
- GitHub Check: semgrep/ci
- GitHub Check: Analyze (javascript-typescript)
- GitHub Check: semgrep-cloud-platform/scan
- GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (2)
packages/clerk-js/vitest.config.mts (2)
27-27: New test-time define looks goodAdding
__BUILD_DISABLE_RHC__follows the existing pattern and won’t affect runtime since it’s test-only here.
26-31: Define flags are already present in Rspack config—no action needed• In packages/clerk-js/rspack.config.js (line 60) the
DefinePluginincludes
__BUILD_DISABLE_RHC__: JSON.stringify(disableRHC)and
__BUILD_VARIANT_CHIPS__: variant === variants.clerkCHIPS, matching vitest.config.mts
• No other bundler inpackages/clerk-jsusesdefineflags beyond Vite and Rspack
Description
Fixes: USER-2591
Adding support for authentication with
@base-org/accountSDKTODO:
Checklist
pnpm testruns as expected.pnpm buildruns as expected.Type of change
Summary by CodeRabbit
New Features
Chores