@b3dotfun/sdk 0.0.88-alpha.2 → 0.0.88-alpha.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/dist/cjs/global-account/react/components/B3Provider/RelayKitProviderWrapper.js +3 -1
  2. package/dist/cjs/global-account/react/components/SignInWithB3/SignInWithB3Flow.js +76 -20
  3. package/dist/cjs/global-account/react/components/TurnkeyAuthModal.js +3 -1
  4. package/dist/cjs/global-account/react/hooks/index.d.ts +1 -0
  5. package/dist/cjs/global-account/react/hooks/index.js +3 -1
  6. package/dist/cjs/global-account/react/hooks/useAuth.d.ts +76 -0
  7. package/dist/cjs/global-account/react/hooks/useAuth.js +338 -0
  8. package/dist/cjs/global-account/react/hooks/useTWAuth.d.ts +3 -0
  9. package/dist/cjs/global-account/react/hooks/useTWAuth.js +8 -0
  10. package/dist/cjs/global-account/react/hooks/useTurnkeyAuth.js +50 -22
  11. package/dist/esm/global-account/react/components/B3Provider/RelayKitProviderWrapper.js +3 -1
  12. package/dist/esm/global-account/react/components/SignInWithB3/SignInWithB3Flow.js +76 -20
  13. package/dist/esm/global-account/react/components/TurnkeyAuthModal.js +5 -3
  14. package/dist/esm/global-account/react/hooks/index.d.ts +1 -0
  15. package/dist/esm/global-account/react/hooks/index.js +1 -0
  16. package/dist/esm/global-account/react/hooks/useAuth.d.ts +76 -0
  17. package/dist/esm/global-account/react/hooks/useAuth.js +332 -0
  18. package/dist/esm/global-account/react/hooks/useTWAuth.d.ts +3 -0
  19. package/dist/esm/global-account/react/hooks/useTWAuth.js +8 -0
  20. package/dist/esm/global-account/react/hooks/useTurnkeyAuth.js +50 -22
  21. package/dist/types/global-account/react/hooks/index.d.ts +1 -0
  22. package/dist/types/global-account/react/hooks/useAuth.d.ts +76 -0
  23. package/dist/types/global-account/react/hooks/useTWAuth.d.ts +3 -0
  24. package/package.json +1 -1
  25. package/src/global-account/react/components/B3Provider/RelayKitProviderWrapper.tsx +4 -1
  26. package/src/global-account/react/components/SignInWithB3/SignInWithB3Flow.tsx +168 -100
  27. package/src/global-account/react/components/TurnkeyAuthModal.tsx +7 -4
  28. package/src/global-account/react/hooks/index.ts +1 -0
  29. package/src/global-account/react/hooks/useAuth.ts +380 -0
  30. package/src/global-account/react/hooks/useTWAuth.tsx +10 -0
  31. package/src/global-account/react/hooks/useTurnkeyAuth.ts +54 -23
@@ -3,6 +3,7 @@ import { Loading, useAuthentication, useAuthStore, useB3Config, useGetAllTWSigne
3
3
  import { debugB3React } from "../../../../shared/utils/debug.js";
4
4
  import { useCallback, useEffect, useState } from "react";
5
5
  import { useActiveAccount } from "thirdweb/react";
6
+ import { TurnkeyAuthModal } from "../TurnkeyAuthModal.js";
6
7
  import { SignInWithB3Privy } from "./SignInWithB3Privy.js";
7
8
  import { LoginStep, LoginStepContainer } from "./steps/LoginStep.js";
8
9
  import { LoginStepCustom } from "./steps/LoginStepCustom.js";
@@ -21,7 +22,9 @@ export function SignInWithB3Flow({ strategies, onLoginSuccess, onSessionKeySucce
21
22
  const account = useActiveAccount();
22
23
  const isAuthenticating = useAuthStore(state => state.isAuthenticating);
23
24
  const isAuthenticated = useAuthStore(state => state.isAuthenticated);
25
+ const setIsAuthenticated = useAuthStore(state => state.setIsAuthenticated);
24
26
  const isConnected = useAuthStore(state => state.isConnected);
27
+ const setIsConnected = useAuthStore(state => state.setIsConnected);
25
28
  const setJustCompletedLogin = useAuthStore(state => state.setJustCompletedLogin);
26
29
  const [refetchCount, setRefetchCount] = useState(0);
27
30
  const [refetchError, setRefetchError] = useState(null);
@@ -54,7 +57,9 @@ export function SignInWithB3Flow({ strategies, onLoginSuccess, onSessionKeySucce
54
57
  refetchSigners();
55
58
  setRefetchQueued(false);
56
59
  }, backoffDelay);
57
- }, [refetchCount, refetchSigners, onError, setRefetchQueued, refetchQueued]);
60
+ // State setters are stable and don't need to be in dependencies
61
+ // eslint-disable-next-line react-hooks/exhaustive-deps
62
+ }, [refetchCount, refetchSigners, onError, refetchQueued]);
58
63
  // Extract the completion flow logic to be reused
59
64
  const handlePostTurnkeyFlow = useCallback(() => {
60
65
  debug("Running post-Turnkey flow logic");
@@ -123,6 +128,10 @@ export function SignInWithB3Flow({ strategies, onLoginSuccess, onSessionKeySucce
123
128
  debug("Refetching user after Turnkey success...");
124
129
  await refetchUser();
125
130
  debug("User refetched successfully");
131
+ // Set authentication and connection state so UI updates properly
132
+ setIsAuthenticated(true);
133
+ setIsConnected(true);
134
+ setJustCompletedLogin(true);
126
135
  // After user data is refreshed, close Turnkey modal and go back to sign-in flow
127
136
  debug("Switching back to signInWithB3 modal");
128
137
  setB3ModalContentType({
@@ -141,7 +150,6 @@ export function SignInWithB3Flow({ strategies, onLoginSuccess, onSessionKeySucce
141
150
  // The useEffect will re-run with updated user data to complete the sign-in process
142
151
  }, [
143
152
  refetchUser,
144
- setB3ModalContentType,
145
153
  strategies,
146
154
  onLoginSuccess,
147
155
  onSessionKeySuccess,
@@ -152,6 +160,10 @@ export function SignInWithB3Flow({ strategies, onLoginSuccess, onSessionKeySucce
152
160
  closeAfterLogin,
153
161
  source,
154
162
  signersEnabled,
163
+ setB3ModalContentType,
164
+ setIsAuthenticated,
165
+ setIsConnected,
166
+ setJustCompletedLogin,
155
167
  ]);
156
168
  // Handle post-login flow after signers are loaded
157
169
  useEffect(() => {
@@ -169,15 +181,20 @@ export function SignInWithB3Flow({ strategies, onLoginSuccess, onSessionKeySucce
169
181
  if (closeAfterLogin) {
170
182
  setJustCompletedLogin(true);
171
183
  }
172
- // Check if we should show Turnkey login form
173
- // Show if enableTurnkey is true AND user just logged in AND hasn't completed Turnkey auth in this session
184
+ // Check if we should show Turnkey login form as SECONDARY option (after wallet connection)
185
+ // This only applies when:
186
+ // - enableTurnkey={true} is set on B3Provider
187
+ // - NEXT_PUBLIC_TURNKEY_PRIMARY is NOT set to true (otherwise Turnkey shows as primary)
188
+ // - User just logged in AND hasn't completed Turnkey auth in this session
174
189
  // For new users (!turnkeyId): Show email form
175
190
  // For returning users (turnkeyId && turnkeyEmail): Auto-skip to OTP
176
191
  // Also check that we're not already showing the Turnkey modal
177
192
  const hasTurnkeyId = user?.partnerIds?.turnkeyId;
178
193
  const hasTurnkeyEmail = !!user?.email;
179
194
  const isTurnkeyModalCurrentlyOpen = contentType?.type === "turnkeyAuth";
195
+ const isTurnkeyPrimary = process.env.NEXT_PUBLIC_TURNKEY_PRIMARY === "true";
180
196
  const shouldShowTurnkeyModal = enableTurnkey &&
197
+ !isTurnkeyPrimary &&
181
198
  user &&
182
199
  !turnkeyAuthCompleted &&
183
200
  !isTurnkeyModalCurrentlyOpen &&
@@ -204,7 +221,9 @@ export function SignInWithB3Flow({ strategies, onLoginSuccess, onSessionKeySucce
204
221
  // Normal flow continues after Turnkey auth is complete (or if not needed)
205
222
  handlePostTurnkeyFlow();
206
223
  }
207
- }, [
224
+ },
225
+ // eslint-disable-next-line react-hooks/exhaustive-deps
226
+ [
208
227
  signers,
209
228
  isFetchingSigners,
210
229
  partnerId,
@@ -220,11 +239,10 @@ export function SignInWithB3Flow({ strategies, onLoginSuccess, onSessionKeySucce
220
239
  isAuthenticating,
221
240
  isAuthenticated,
222
241
  isOpen,
223
- setJustCompletedLogin,
224
242
  user,
225
243
  enableTurnkey,
226
244
  turnkeyAuthCompleted,
227
- handleTurnkeySuccess,
245
+ // handleTurnkeySuccess, // This is causing infinite loops
228
246
  contentType,
229
247
  handlePostTurnkeyFlow,
230
248
  ]);
@@ -241,7 +259,9 @@ export function SignInWithB3Flow({ strategies, onLoginSuccess, onSessionKeySucce
241
259
  if (closeAfterLogin && sessionKeyAdded) {
242
260
  setB3ModalOpen(false);
243
261
  }
244
- }, [closeAfterLogin, sessionKeyAdded, setB3ModalOpen]);
262
+ // setB3ModalOpen is stable
263
+ // eslint-disable-next-line react-hooks/exhaustive-deps
264
+ }, [closeAfterLogin, sessionKeyAdded]);
245
265
  const onSessionKeySuccessEnhanced = useCallback(() => {
246
266
  onSessionKeySuccess?.();
247
267
  setB3ModalContentType({
@@ -287,21 +307,57 @@ export function SignInWithB3Flow({ strategies, onLoginSuccess, onSessionKeySucce
287
307
  if (refetchError) {
288
308
  content = (_jsx(LoginStepContainer, { partnerId: partnerId, children: _jsx("div", { className: "p-4 text-center text-red-500", children: refetchError }) }));
289
309
  }
290
- else if (isAuthenticating || (isFetchingSigners && step === "login") || source === "requestPermissions") {
291
- content = (_jsx(LoginStepContainer, { partnerId: partnerId, children: _jsx("div", { className: "my-8 flex min-h-[350px] items-center justify-center", children: _jsx(Loading, { variant: "white", size: "lg" }) }) }));
292
- }
293
310
  else if (step === "login") {
294
- // Custom strategy
295
- if (strategies?.[0] === "privy") {
296
- content = _jsx(SignInWithB3Privy, { onSuccess: handleLoginSuccess, chain: chain });
297
- }
298
- else if (strategies) {
299
- // Strategies are explicitly provided
300
- content = (_jsx(LoginStepCustom, { strategies: strategies, chain: chain, onSuccess: handleLoginSuccess, onError: onError, automaticallySetFirstEoa: !!automaticallySetFirstEoa }));
311
+ // PRIORITY: If NEXT_PUBLIC_TURNKEY_PRIMARY is true, show Turnkey modal FIRST as the primary authentication option
312
+ // Setting NEXT_PUBLIC_TURNKEY_PRIMARY="true" implicitly enables Turnkey
313
+ const isTurnkeyPrimary = process.env.NEXT_PUBLIC_TURNKEY_PRIMARY === "true";
314
+ const shouldShowTurnkeyFirst = isTurnkeyPrimary && !turnkeyAuthCompleted;
315
+ if (shouldShowTurnkeyFirst) {
316
+ // Don't show loading spinner for Turnkey - let the modal handle its own loading state
317
+ // This prevents the infinite loop where isAuthenticating causes the modal to be replaced
318
+ debug("Showing Turnkey as primary authentication option", {
319
+ isTurnkeyPrimary,
320
+ turnkeyAuthCompleted,
321
+ isAuthenticated,
322
+ });
323
+ // Show Turnkey authentication as primary option
324
+ content = (_jsx(LoginStepContainer, { partnerId: partnerId, children: _jsx(TurnkeyAuthModal, { onSuccess: async (authenticatedUser) => {
325
+ debug("Turnkey authentication successful in primary flow", { authenticatedUser });
326
+ setTurnkeyAuthCompleted(true);
327
+ // After Turnkey auth, refetch user to get the full user object
328
+ await refetchUser();
329
+ // User is now authenticated via Turnkey
330
+ // Set both isAuthenticated and isConnected to true so UI updates properly
331
+ // Wallet connection is optional and can happen later for signing transactions
332
+ setIsAuthenticated(true);
333
+ setIsConnected(true);
334
+ setJustCompletedLogin(true);
335
+ // Call the login success callback
336
+ onLoginSuccess?.({});
337
+ }, onClose: () => {
338
+ // If user closes Turnkey modal, they can still use wallet connection as fallback
339
+ setTurnkeyAuthCompleted(true);
340
+ }, initialEmail: "", skipToOtp: false }) }));
301
341
  }
302
342
  else {
303
- // Default to handle all strategies we support
304
- content = _jsx(LoginStep, { chain: chain, onSuccess: handleLoginSuccess, onError: onError });
343
+ // Show loading spinner only if not in Turnkey flow
344
+ if (isAuthenticating || (isFetchingSigners && step === "login") || source === "requestPermissions") {
345
+ content = (_jsx(LoginStepContainer, { partnerId: partnerId, children: _jsx("div", { className: "my-8 flex min-h-[350px] items-center justify-center", children: _jsx(Loading, { variant: "white", size: "lg" }) }) }));
346
+ }
347
+ else {
348
+ // Custom strategy
349
+ if (strategies?.[0] === "privy") {
350
+ content = _jsx(SignInWithB3Privy, { onSuccess: handleLoginSuccess, chain: chain });
351
+ }
352
+ else if (strategies) {
353
+ // Strategies are explicitly provided
354
+ content = (_jsx(LoginStepCustom, { strategies: strategies, chain: chain, onSuccess: handleLoginSuccess, onError: onError, automaticallySetFirstEoa: !!automaticallySetFirstEoa }));
355
+ }
356
+ else {
357
+ // Default to handle all strategies we support
358
+ content = _jsx(LoginStep, { chain: chain, onSuccess: handleLoginSuccess, onError: onError });
359
+ }
360
+ }
305
361
  }
306
362
  }
307
363
  return content;
@@ -1,5 +1,5 @@
1
- import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
- import { useState, useEffect, useRef } from "react";
1
+ import { jsxs as _jsxs, jsx as _jsx, Fragment as _Fragment } from "react/jsx-runtime";
2
+ import { useEffect, useRef, useState } from "react";
3
3
  import { useTurnkeyAuth } from "../hooks/useTurnkeyAuth.js";
4
4
  export function TurnkeyAuthModal({ onClose, onSuccess, initialEmail = "", skipToOtp = false }) {
5
5
  const [step, setStep] = useState(skipToOtp ? "otp" : "email");
@@ -77,5 +77,7 @@ export function TurnkeyAuthModal({ onClose, onSuccess, initialEmail = "", skipTo
77
77
  console.error("Failed to resend OTP:", err);
78
78
  }
79
79
  };
80
- return (_jsxs("div", { className: "font-neue-montreal p-8", children: [step === "email" && (_jsxs(_Fragment, { children: [_jsx("h2", { className: "mb-6 text-center text-2xl font-bold text-gray-900 dark:text-white", children: "Setup your AnySpend Wallet" }), _jsxs("div", { className: "mb-6 space-y-3 text-center text-sm text-gray-600 dark:text-gray-400", children: [_jsxs("p", { children: ["AnySpend uses a secure,", _jsx("br", {}), "embedded wallet to fund your workflows."] }), _jsxs("p", { children: ["Please provide an email address to secure", _jsx("br", {}), "your wallet."] })] }), _jsxs("form", { onSubmit: handleEmailSubmit, className: "space-y-4", children: [_jsx("div", { children: _jsx("input", { type: "email", placeholder: "email", value: email, onChange: e => setEmail(e.target.value), required: true, disabled: isLoading, className: "w-full rounded-lg border border-gray-300 px-4 py-3 text-center text-gray-900 placeholder-gray-400 focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-500/20 disabled:cursor-not-allowed disabled:bg-gray-50 dark:border-gray-700 dark:bg-gray-800 dark:text-white dark:placeholder-gray-500" }) }), error && (_jsx("div", { className: "rounded-md bg-red-50 p-3 text-sm text-red-800 dark:bg-red-900/20 dark:text-red-400", children: error })), _jsx("button", { type: "submit", disabled: isLoading || !email, className: "w-full rounded-lg bg-blue-600 px-6 py-3 font-semibold text-white transition-all duration-200 hover:bg-blue-700 disabled:cursor-not-allowed disabled:bg-gray-300 dark:disabled:bg-gray-700", children: isLoading ? (_jsxs("span", { className: "flex items-center justify-center gap-2", children: [_jsx("div", { className: "h-4 w-4 animate-spin rounded-full border-2 border-white border-t-transparent" }), "Sending..."] })) : ("Continue") })] })] })), step === "otp" && (_jsxs(_Fragment, { children: [_jsx("h2", { className: "mb-4 text-center text-2xl font-bold text-gray-900 dark:text-white", children: "2FA Security" }), _jsx("div", { className: "mb-6 space-y-3 text-center text-sm text-gray-600 dark:text-gray-400", children: _jsxs("p", { children: ["AnySpend uses a secure,", _jsx("br", {}), "embedded wallet to fund your workflows.", _jsx("br", {}), "Please provide 2FA code sent to your email."] }) }), _jsxs("form", { onSubmit: handleOtpSubmit, className: "space-y-4", children: [_jsx("div", { children: _jsx("input", { type: "text", placeholder: "Enter code", value: otpCode, onChange: e => setOtpCode(e.target.value.toUpperCase()), required: true, disabled: isLoading, autoFocus: true, className: "w-full rounded-lg border border-gray-300 px-4 py-3 text-center font-mono text-lg uppercase tracking-wider text-gray-900 placeholder-gray-400 focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-500/20 disabled:cursor-not-allowed disabled:bg-gray-50 dark:border-gray-700 dark:bg-gray-800 dark:text-white dark:placeholder-gray-500", maxLength: 20 }) }), error && (_jsx("div", { className: "rounded-md bg-red-50 p-3 text-sm text-red-800 dark:bg-red-900/20 dark:text-red-400", children: error })), _jsxs("div", { className: "flex flex-col gap-2", children: [_jsx("button", { type: "submit", disabled: isLoading || !otpCode, className: "w-full rounded-lg bg-blue-600 px-6 py-3 font-semibold text-white transition-all duration-200 hover:bg-blue-700 disabled:cursor-not-allowed disabled:bg-gray-300 dark:disabled:bg-gray-700", children: isLoading ? (_jsxs("span", { className: "flex items-center justify-center gap-2", children: [_jsx("div", { className: "h-4 w-4 animate-spin rounded-full border-2 border-white border-t-transparent" }), "Verifying..."] })) : ("Confirm") }), _jsx("button", { type: "button", onClick: handleResendOtp, disabled: isLoading, className: "text-sm text-blue-600 hover:text-blue-700 hover:underline disabled:cursor-not-allowed disabled:text-gray-400 dark:text-blue-400 dark:hover:text-blue-300", children: "Resend code" })] })] })] })), step === "success" && (_jsxs("div", { className: "text-center", children: [_jsx("div", { className: "mb-6 flex items-center justify-center", children: _jsx("div", { className: "flex h-16 w-16 items-center justify-center rounded-full bg-green-100 dark:bg-green-900/20", children: _jsx("svg", { className: "h-8 w-8 text-green-600 dark:text-green-400", fill: "none", viewBox: "0 0 24 24", stroke: "currentColor", children: _jsx("path", { strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: 2, d: "M5 13l4 4L19 7" }) }) }) }), _jsx("h2", { className: "mb-2 text-2xl font-bold text-gray-900 dark:text-white", children: "Successfully Authenticated!" }), _jsx("p", { className: "text-sm text-gray-600 dark:text-gray-400", children: "Redirecting..." })] }))] }));
80
+ const isTurnkeyPrimary = process.env.NEXT_PUBLIC_TURNKEY_PRIMARY === "true";
81
+ const walletBrand = isTurnkeyPrimary ? "Smart Wallet" : "AnySpend Wallet";
82
+ return (_jsxs("div", { className: "font-neue-montreal p-8", children: [step === "email" && (_jsxs(_Fragment, { children: [_jsxs("h2", { className: "mb-6 text-center text-2xl font-bold text-gray-900 dark:text-white", children: ["Setup your ", walletBrand] }), _jsxs("div", { className: "mb-6 space-y-3 text-center text-sm text-gray-600 dark:text-gray-400", children: [_jsxs("p", { children: [isTurnkeyPrimary ? "We use a secure," : "AnySpend uses a secure,", _jsx("br", {}), "embedded wallet to fund your workflows."] }), _jsxs("p", { children: ["Please provide an email address to secure", _jsx("br", {}), "your wallet."] })] }), _jsxs("form", { onSubmit: handleEmailSubmit, className: "space-y-4", children: [_jsx("div", { children: _jsx("input", { type: "email", placeholder: "email", value: email, onChange: e => setEmail(e.target.value), required: true, disabled: isLoading, className: "w-full rounded-lg border border-gray-300 px-4 py-3 text-center text-gray-900 placeholder-gray-400 focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-500/20 disabled:cursor-not-allowed disabled:bg-gray-50 dark:border-gray-700 dark:bg-gray-800 dark:text-white dark:placeholder-gray-500" }) }), error && (_jsx("div", { className: "rounded-md bg-red-50 p-3 text-sm text-red-800 dark:bg-red-900/20 dark:text-red-400", children: error })), _jsx("button", { type: "submit", disabled: isLoading || !email, className: "w-full rounded-lg bg-blue-600 px-6 py-3 font-semibold text-white transition-all duration-200 hover:bg-blue-700 disabled:cursor-not-allowed disabled:bg-gray-300 dark:disabled:bg-gray-700", children: isLoading ? (_jsxs("span", { className: "flex items-center justify-center gap-2", children: [_jsx("div", { className: "h-4 w-4 animate-spin rounded-full border-2 border-white border-t-transparent" }), "Sending..."] })) : ("Continue") })] })] })), step === "otp" && (_jsxs(_Fragment, { children: [_jsx("h2", { className: "mb-4 text-center text-2xl font-bold text-gray-900 dark:text-white", children: "2FA Security" }), _jsx("div", { className: "mb-6 space-y-3 text-center text-sm text-gray-600 dark:text-gray-400", children: _jsxs("p", { children: [isTurnkeyPrimary ? "We use a secure," : "AnySpend uses a secure,", _jsx("br", {}), "embedded wallet to fund your workflows.", _jsx("br", {}), "Please provide 2FA code sent to your email."] }) }), _jsxs("form", { onSubmit: handleOtpSubmit, className: "space-y-4", children: [_jsx("div", { children: _jsx("input", { type: "text", placeholder: "Enter code", value: otpCode, onChange: e => setOtpCode(e.target.value.toUpperCase()), required: true, disabled: isLoading, autoFocus: true, className: "w-full rounded-lg border border-gray-300 px-4 py-3 text-center font-mono text-lg uppercase tracking-wider text-gray-900 placeholder-gray-400 focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-500/20 disabled:cursor-not-allowed disabled:bg-gray-50 dark:border-gray-700 dark:bg-gray-800 dark:text-white dark:placeholder-gray-500", maxLength: 20 }) }), error && (_jsx("div", { className: "rounded-md bg-red-50 p-3 text-sm text-red-800 dark:bg-red-900/20 dark:text-red-400", children: error })), _jsxs("div", { className: "flex flex-col gap-2", children: [_jsx("button", { type: "submit", disabled: isLoading || !otpCode, className: "w-full rounded-lg bg-blue-600 px-6 py-3 font-semibold text-white transition-all duration-200 hover:bg-blue-700 disabled:cursor-not-allowed disabled:bg-gray-300 dark:disabled:bg-gray-700", children: isLoading ? (_jsxs("span", { className: "flex items-center justify-center gap-2", children: [_jsx("div", { className: "h-4 w-4 animate-spin rounded-full border-2 border-white border-t-transparent" }), "Verifying..."] })) : ("Confirm") }), _jsx("button", { type: "button", onClick: handleResendOtp, disabled: isLoading, className: "text-sm text-blue-600 hover:text-blue-700 hover:underline disabled:cursor-not-allowed disabled:text-gray-400 dark:text-blue-400 dark:hover:text-blue-300", children: "Resend code" })] })] })] })), step === "success" && (_jsxs("div", { className: "text-center", children: [_jsx("div", { className: "mb-6 flex items-center justify-center", children: _jsx("div", { className: "flex h-16 w-16 items-center justify-center rounded-full bg-green-100 dark:bg-green-900/20", children: _jsx("svg", { className: "h-8 w-8 text-green-600 dark:text-green-400", fill: "none", viewBox: "0 0 24 24", stroke: "currentColor", children: _jsx("path", { strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: 2, d: "M5 13l4 4L19 7" }) }) }) }), _jsx("h2", { className: "mb-2 text-2xl font-bold text-gray-900 dark:text-white", children: "Successfully Authenticated!" }), _jsx("p", { className: "text-sm text-gray-600 dark:text-gray-400", children: "Redirecting..." })] }))] }));
81
83
  }
@@ -3,6 +3,7 @@ export { useAccountAssets } from "./useAccountAssets";
3
3
  export { useAccountWallet } from "./useAccountWallet";
4
4
  export { useAddTWSessionKey } from "./useAddTWSessionKey";
5
5
  export { useAnalytics } from "./useAnalytics";
6
+ export { useAuth } from "./useAuth";
6
7
  export { useAuthentication } from "./useAuthentication";
7
8
  export { useB3BalanceFromAddresses } from "./useB3BalanceFromAddresses";
8
9
  export { useB3EnsName } from "./useB3EnsName";
@@ -3,6 +3,7 @@ export { useAccountAssets } from "./useAccountAssets.js";
3
3
  export { useAccountWallet } from "./useAccountWallet.js";
4
4
  export { useAddTWSessionKey } from "./useAddTWSessionKey.js";
5
5
  export { useAnalytics } from "./useAnalytics.js";
6
+ export { useAuth } from "./useAuth.js";
6
7
  export { useAuthentication } from "./useAuthentication.js";
7
8
  export { useB3BalanceFromAddresses } from "./useB3BalanceFromAddresses.js";
8
9
  export { useB3EnsName } from "./useB3EnsName.js";
@@ -0,0 +1,76 @@
1
+ import { Wallet } from "thirdweb/wallets";
2
+ import { preAuthenticate } from "thirdweb/wallets/in-app";
3
+ /**
4
+ * Unified authentication hook that uses Turnkey for authentication
5
+ * This replaces the previous Thirdweb-based authentication
6
+ *
7
+ * This hook provides 1:1 feature parity with useAuthentication.ts
8
+ */
9
+ export declare function useAuth(): {
10
+ authenticate: (turnkeySessionJwt: string, partnerId: string) => Promise<import("@feathersjs/authentication").AuthenticationResult>;
11
+ reAuthenticate: () => Promise<import("@feathersjs/authentication").AuthenticationResult>;
12
+ logout: (callback?: () => void) => Promise<void>;
13
+ isAuthenticated: boolean;
14
+ isReady: boolean;
15
+ isConnecting: boolean;
16
+ isConnected: boolean;
17
+ wallet: import("thirdweb/dist/types/wallets/in-app/core/wallet/types").EcosystemWallet;
18
+ preAuthenticate: typeof preAuthenticate;
19
+ connect: (_walleAutoConnectedWith: Wallet, allConnectedWallets: Wallet[]) => Promise<void>;
20
+ isAuthenticating: boolean;
21
+ onConnect: (_walleAutoConnectedWith: Wallet, allConnectedWallets: Wallet[]) => Promise<void>;
22
+ user: {
23
+ email?: string | undefined;
24
+ username?: string | undefined;
25
+ telNumber?: string | undefined;
26
+ ens?: string | undefined;
27
+ avatar?: string | undefined;
28
+ preferences?: {} | undefined;
29
+ referredBy?: string | {} | undefined;
30
+ sourceApp?: string | undefined;
31
+ referralCode?: string | undefined;
32
+ userGroups?: number[] | undefined;
33
+ isMigratedFromBSMNT?: boolean | undefined;
34
+ privyLinkedAccounts?: {
35
+ name?: string | undefined;
36
+ address?: string | undefined;
37
+ email?: string | undefined;
38
+ chain_type?: string | undefined;
39
+ lv?: number | undefined;
40
+ wallet_client_type?: string | undefined;
41
+ smart_wallet_type?: string | undefined;
42
+ subject?: string | undefined;
43
+ type: string;
44
+ }[] | undefined;
45
+ twProfiles?: {
46
+ type: string;
47
+ details: {
48
+ id?: string | undefined;
49
+ name?: string | undefined;
50
+ address?: string | undefined;
51
+ email?: string | undefined;
52
+ username?: string | undefined;
53
+ phone?: string | undefined;
54
+ fid?: string | undefined;
55
+ };
56
+ }[] | undefined;
57
+ turnkeySubOrgs?: {
58
+ hasDelegatedUser?: boolean | undefined;
59
+ subOrgId: string;
60
+ accounts: Record<string, any>[];
61
+ }[] | undefined;
62
+ _id: string | {};
63
+ userId: string;
64
+ smartAccountAddress: string;
65
+ createdAt: number;
66
+ updatedAt: number;
67
+ partnerIds: {
68
+ privyId?: string | undefined;
69
+ thirdwebId?: string | undefined;
70
+ turnkeyId?: string | undefined;
71
+ turnkeyOtpId?: string | undefined;
72
+ };
73
+ } | undefined;
74
+ refetchUser: () => Promise<import("@feathersjs/authentication").AuthenticationResult>;
75
+ setUser: (newUser?: import("@b3dotfun/b3-api").Users) => void;
76
+ };
@@ -0,0 +1,332 @@
1
+ import app from "../../../global-account/app.js";
2
+ import { authenticateWithB3JWT } from "../../../global-account/bsmnt.js";
3
+ import { useAuthStore } from "../../../global-account/react/index.js";
4
+ import { ecosystemWalletId } from "../../../shared/constants/index.js";
5
+ import { debugB3React } from "../../../shared/utils/debug.js";
6
+ import { client } from "../../../shared/utils/thirdweb.js";
7
+ import { getConnectors } from "@wagmi/core";
8
+ import { useCallback, useContext, useEffect, useRef } from "react";
9
+ import { useActiveWallet, useAutoConnect, useConnectedWallets, useDisconnect, useSetActiveWallet, } from "thirdweb/react";
10
+ import { ecosystemWallet } from "thirdweb/wallets";
11
+ import { preAuthenticate } from "thirdweb/wallets/in-app";
12
+ import { useAccount, useConnect, useSwitchAccount } from "wagmi";
13
+ import { LocalSDKContext } from "../components/B3Provider/LocalSDKProvider.js";
14
+ import { useB3 } from "../components/B3Provider/useB3.js";
15
+ import { createWagmiConfig } from "../utils/createWagmiConfig.js";
16
+ import { useSearchParam } from "./useSearchParamsSSR.js";
17
+ import { useUserQuery } from "./useUserQuery.js";
18
+ const debug = debugB3React("useAuth");
19
+ /**
20
+ * Unified authentication hook that uses Turnkey for authentication
21
+ * This replaces the previous Thirdweb-based authentication
22
+ *
23
+ * This hook provides 1:1 feature parity with useAuthentication.ts
24
+ */
25
+ export function useAuth() {
26
+ const { onConnectCallback } = useContext(LocalSDKContext);
27
+ const { disconnect } = useDisconnect();
28
+ const wallets = useConnectedWallets();
29
+ const activeWallet = useActiveWallet();
30
+ const isAuthenticated = useAuthStore(state => state.isAuthenticated);
31
+ const setIsAuthenticated = useAuthStore(state => state.setIsAuthenticated);
32
+ const setIsConnected = useAuthStore(state => state.setIsConnected);
33
+ const isConnecting = useAuthStore(state => state.isConnecting);
34
+ const isConnected = useAuthStore(state => state.isConnected);
35
+ const isAuthenticating = useAuthStore(state => state.isAuthenticating);
36
+ const setIsAuthenticating = useAuthStore(state => state.setIsAuthenticating);
37
+ const setHasStartedConnecting = useAuthStore(state => state.setHasStartedConnecting);
38
+ const setActiveWallet = useSetActiveWallet();
39
+ const hasStartedConnecting = useAuthStore(state => state.hasStartedConnecting);
40
+ const useAutoConnectLoadingPrevious = useRef(false);
41
+ const referralCode = useSearchParam("referralCode");
42
+ const { partnerId } = useB3();
43
+ const wagmiConfig = createWagmiConfig({ partnerId });
44
+ const { connect } = useConnect();
45
+ const activeWagmiAccount = useAccount();
46
+ const { switchAccount } = useSwitchAccount();
47
+ const { user, setUser } = useUserQuery();
48
+ debug("@@activeWagmiAccount", activeWagmiAccount);
49
+ const wallet = ecosystemWallet(ecosystemWalletId, {
50
+ partnerId: partnerId,
51
+ });
52
+ /**
53
+ * Re-authenticate using existing session
54
+ * Also updates user state and authenticates with BSMNT
55
+ */
56
+ const reAuthenticate = useCallback(async () => {
57
+ debug("Re-authenticating...");
58
+ try {
59
+ const response = await app.reAuthenticate();
60
+ debug("Re-authentication successful", response);
61
+ // Update user state if user data exists
62
+ if (response.user) {
63
+ setUser(response.user);
64
+ debug("User state updated", response.user);
65
+ }
66
+ // Authenticate with BSMNT
67
+ try {
68
+ const b3Jwt = await authenticateWithB3JWT(response.accessToken);
69
+ debug("BSMNT re-authentication successful", b3Jwt);
70
+ }
71
+ catch (bsmntError) {
72
+ // BSMNT authentication failure shouldn't block the main auth flow
73
+ debug("BSMNT re-authentication failed (non-critical)", bsmntError);
74
+ }
75
+ return response;
76
+ }
77
+ catch (err) {
78
+ debug("Re-authentication failed", err);
79
+ throw err;
80
+ }
81
+ }, [setUser]);
82
+ const syncWagmi = useCallback(async () => {
83
+ function syncWagmiFunc() {
84
+ const connectors = getConnectors(wagmiConfig);
85
+ debug("@@syncWagmi", {
86
+ connectors,
87
+ wallets,
88
+ });
89
+ // For each that matchs a TW wallet on wallets, connect to the wagmi connector
90
+ // or, since ecosystem wallets is separate, connect those via in-app-wallet from wagmi
91
+ connectors.forEach(async (connector) => {
92
+ const twWallet = wallets.find(wallet => wallet.id === connector.id || connector.id === "in-app-wallet");
93
+ // If no TW wallet, do not prompt the user to connect
94
+ if (!twWallet) {
95
+ return;
96
+ }
97
+ // Metamask will prompt to connect, we can just switch accounts here.
98
+ if (connector.id === "io.metamask") {
99
+ return switchAccount({ connector });
100
+ }
101
+ if (
102
+ // If it's not an in-app wallet or it is the ecosystem wallet, connect
103
+ connector.id !== "in-app-wallet" ||
104
+ (connector.id === "in-app-wallet" && twWallet.id === ecosystemWalletId)) {
105
+ try {
106
+ const options = {
107
+ wallet: twWallet, // the connected wallet
108
+ };
109
+ debug("@@syncWagmi:connecting", { twWallet, connector });
110
+ connect({
111
+ connector,
112
+ ...options,
113
+ });
114
+ }
115
+ catch (error) {
116
+ console.error("@@syncWagmi:error", error);
117
+ }
118
+ }
119
+ else {
120
+ debug("@@syncWagmi:not-connecting", connector);
121
+ }
122
+ });
123
+ }
124
+ syncWagmiFunc();
125
+ // wagmi config shouldn't change
126
+ // eslint-disable-next-line react-hooks/exhaustive-deps
127
+ }, [partnerId, wallets]);
128
+ useEffect(() => {
129
+ syncWagmi();
130
+ }, [wallets, syncWagmi]);
131
+ /**
132
+ * Authenticate user using Turnkey
133
+ * Note: This no longer requires a wallet for authentication.
134
+ * Wallets are still used for signing transactions, but authentication is done via Turnkey email OTP.
135
+ *
136
+ * For backward compatibility, this function still accepts a wallet parameter,
137
+ * but it's not used for authentication anymore.
138
+ */
139
+ const authenticateUser = useCallback(async () => {
140
+ setHasStartedConnecting(true);
141
+ // Try to re-authenticate first
142
+ try {
143
+ const userAuth = await reAuthenticate();
144
+ setUser(userAuth.user);
145
+ setIsAuthenticated(true);
146
+ setIsAuthenticating(false);
147
+ debug("Re-authenticated successfully", { userAuth });
148
+ // Authenticate on BSMNT with B3 JWT
149
+ const b3Jwt = await authenticateWithB3JWT(userAuth.accessToken);
150
+ debug("@@b3Jwt", b3Jwt);
151
+ return userAuth;
152
+ }
153
+ catch (error) {
154
+ // If re-authentication fails, user needs to authenticate via Turnkey
155
+ // This should be handled by the Turnkey auth modal/flow
156
+ debug("Re-authentication failed. User needs to authenticate via Turnkey.", error);
157
+ setIsAuthenticated(false);
158
+ setIsAuthenticating(false);
159
+ throw new Error("Authentication required. Please authenticate via Turnkey.");
160
+ }
161
+ }, [reAuthenticate, setIsAuthenticated, setIsAuthenticating, setUser, setHasStartedConnecting]);
162
+ /**
163
+ * Authenticate with Turnkey using email OTP
164
+ * This is the primary authentication method, replacing Thirdweb wallet-based auth
165
+ *
166
+ * This function:
167
+ * 1. Authenticates with FeathersJS (persists session via cookies)
168
+ * 2. Sets user state in the user store (persists to localStorage)
169
+ * 3. Authenticates with BSMNT for basement integration
170
+ */
171
+ const authenticate = useCallback(async (turnkeySessionJwt, partnerId) => {
172
+ if (!turnkeySessionJwt) {
173
+ throw new Error("Turnkey session JWT is required");
174
+ }
175
+ debug("Authenticating with Turnkey JWT", { referralCode, partnerId });
176
+ try {
177
+ // Step 1: Authenticate with FeathersJS (session persisted via cookies)
178
+ const response = await app.authenticate({
179
+ strategy: "turnkey-jwt",
180
+ accessToken: turnkeySessionJwt,
181
+ referralCode,
182
+ partnerId: partnerId,
183
+ });
184
+ debug("Authentication successful", response);
185
+ // Step 2: Set user state (persists to localStorage via Zustand)
186
+ if (response.user) {
187
+ setUser(response.user);
188
+ debug("User state updated", response.user);
189
+ }
190
+ // Step 3: Authenticate with BSMNT for basement integration
191
+ try {
192
+ const b3Jwt = await authenticateWithB3JWT(response.accessToken);
193
+ debug("BSMNT authentication successful", b3Jwt);
194
+ }
195
+ catch (bsmntError) {
196
+ // BSMNT authentication failure shouldn't block the main auth flow
197
+ debug("BSMNT authentication failed (non-critical)", bsmntError);
198
+ }
199
+ return response;
200
+ }
201
+ catch (err) {
202
+ debug("Authentication failed", err);
203
+ throw err;
204
+ }
205
+ }, [referralCode, setUser]);
206
+ /**
207
+ * Handle wallet connection
208
+ * Note: With Turnkey migration, wallet connection is primarily for signing transactions,
209
+ * not for authentication. Authentication should be done separately via Turnkey email OTP.
210
+ */
211
+ /**
212
+ * Handle wallet connection
213
+ * Note: With Turnkey migration, wallet connection is primarily for signing transactions,
214
+ * not for authentication. Authentication should be done separately via Turnkey email OTP.
215
+ */
216
+ const onConnect = useCallback(async (_walleAutoConnectedWith, allConnectedWallets) => {
217
+ debug("@@useAuth:onConnect", { _walleAutoConnectedWith, allConnectedWallets });
218
+ const wallet = allConnectedWallets.find(wallet => wallet.id.startsWith("ecosystem."));
219
+ if (!wallet) {
220
+ throw new Error("No smart wallet found during auto-connect");
221
+ }
222
+ debug("@@useAuth:onConnect", { wallet });
223
+ try {
224
+ setHasStartedConnecting(true);
225
+ setIsConnected(true);
226
+ setIsAuthenticating(true);
227
+ await setActiveWallet(wallet);
228
+ // Try to authenticate user (will use re-authenticate if session exists)
229
+ // If no session exists, authentication will need to happen via Turnkey flow
230
+ try {
231
+ const userAuth = await authenticateUser();
232
+ if (userAuth && onConnectCallback) {
233
+ await onConnectCallback(wallet, userAuth.accessToken);
234
+ }
235
+ }
236
+ catch (authError) {
237
+ // Authentication failed - this is expected if user hasn't authenticated via Turnkey yet
238
+ // The Turnkey auth modal should handle this
239
+ debug("@@useAuth:onConnect:authFailed", { authError });
240
+ // Don't set isAuthenticated to false here - let the Turnkey flow handle it
241
+ }
242
+ }
243
+ catch (error) {
244
+ debug("@@useAuth:onConnect:failed", { error });
245
+ setIsAuthenticated(false);
246
+ setUser(undefined);
247
+ }
248
+ finally {
249
+ setIsAuthenticating(false);
250
+ }
251
+ debug({
252
+ isAuthenticated,
253
+ isAuthenticating,
254
+ isConnected,
255
+ });
256
+ }, [
257
+ onConnectCallback,
258
+ authenticateUser,
259
+ isAuthenticated,
260
+ isAuthenticating,
261
+ isConnected,
262
+ setActiveWallet,
263
+ setHasStartedConnecting,
264
+ setIsAuthenticated,
265
+ setIsAuthenticating,
266
+ setIsConnected,
267
+ setUser,
268
+ ]);
269
+ const logout = useCallback(async (callback) => {
270
+ if (activeWallet) {
271
+ debug("@@logout:activeWallet", activeWallet);
272
+ disconnect(activeWallet);
273
+ debug("@@logout:activeWallet", activeWallet);
274
+ }
275
+ // Log out of each wallet
276
+ wallets.forEach(wallet => {
277
+ console.log("@@logging out", wallet);
278
+ disconnect(wallet);
279
+ });
280
+ // Delete localStorage thirdweb:connected-wallet-ids
281
+ // https://npc-labs.slack.com/archives/C070E6HNG85/p1750185115273099
282
+ if (typeof localStorage !== "undefined") {
283
+ localStorage.removeItem("thirdweb:connected-wallet-ids");
284
+ localStorage.removeItem("wagmi.store");
285
+ localStorage.removeItem("lastAuthProvider");
286
+ localStorage.removeItem("b3-user");
287
+ }
288
+ app.logout();
289
+ debug("@@logout:loggedOut");
290
+ setIsAuthenticated(false);
291
+ setIsConnected(false);
292
+ setUser();
293
+ callback?.();
294
+ }, [activeWallet, disconnect, wallets, setIsAuthenticated, setUser, setIsConnected]);
295
+ const { isLoading: useAutoConnectLoading } = useAutoConnect({
296
+ client,
297
+ wallets: [wallet],
298
+ onConnect,
299
+ onTimeout: () => {
300
+ logout().catch(error => {
301
+ debug("@@useAuth:logout on timeout failed", { error });
302
+ });
303
+ },
304
+ });
305
+ /**
306
+ * useAutoConnectLoading starts as false
307
+ */
308
+ useEffect(() => {
309
+ if (!useAutoConnectLoading && useAutoConnectLoadingPrevious.current && !hasStartedConnecting) {
310
+ setIsAuthenticating(false);
311
+ }
312
+ useAutoConnectLoadingPrevious.current = useAutoConnectLoading;
313
+ }, [useAutoConnectLoading, hasStartedConnecting, setIsAuthenticating]);
314
+ const isReady = isAuthenticated && !isAuthenticating;
315
+ return {
316
+ authenticate,
317
+ reAuthenticate,
318
+ logout,
319
+ isAuthenticated,
320
+ isReady,
321
+ isConnecting,
322
+ isConnected,
323
+ wallet,
324
+ preAuthenticate,
325
+ connect: onConnect,
326
+ isAuthenticating,
327
+ onConnect,
328
+ user,
329
+ refetchUser: authenticateUser,
330
+ setUser,
331
+ };
332
+ }
@@ -1,4 +1,7 @@
1
1
  import { Wallet } from "thirdweb/wallets";
2
+ /**
3
+ * @deprecated Use useAuth() with Turnkey authentication instead
4
+ */
2
5
  export declare function useTWAuth(): {
3
6
  authenticate: (wallet: Wallet, partnerId: string) => Promise<import("@feathersjs/authentication").AuthenticationResult>;
4
7
  };