@b3dotfun/sdk 0.0.82-alpha.3 → 0.0.83-test.0

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 (53) hide show
  1. package/dist/cjs/anyspend/react/components/AnySpend.js +3 -0
  2. package/dist/cjs/anyspend/react/components/AnySpendCustom.js +3 -0
  3. package/dist/cjs/anyspend/react/components/common/CryptoPaymentMethod.js +177 -47
  4. package/dist/cjs/anyspend/react/hooks/useAnyspendFlow.js +3 -0
  5. package/dist/cjs/anyspend/react/hooks/useAutoSetActiveWalletFromWagmi.d.ts +10 -0
  6. package/dist/cjs/anyspend/react/hooks/useAutoSetActiveWalletFromWagmi.js +73 -0
  7. package/dist/cjs/global-account/react/components/SignInWithB3/SignInWithB3Flow.js +57 -12
  8. package/dist/cjs/global-account/react/hooks/index.d.ts +1 -0
  9. package/dist/cjs/global-account/react/hooks/index.js +3 -1
  10. package/dist/cjs/global-account/react/hooks/useAuth.d.ts +76 -0
  11. package/dist/cjs/global-account/react/hooks/useAuth.js +338 -0
  12. package/dist/cjs/global-account/react/hooks/useAuthentication.d.ts +2 -2
  13. package/dist/cjs/global-account/react/hooks/useAuthentication.js +72 -63
  14. package/dist/cjs/global-account/react/hooks/useTWAuth.d.ts +3 -0
  15. package/dist/cjs/global-account/react/hooks/useTWAuth.js +8 -0
  16. package/dist/cjs/global-account/react/hooks/useTurnkeyAuth.js +54 -24
  17. package/dist/cjs/global-account/react/hooks/useUserQuery.d.ts +1 -1
  18. package/dist/esm/anyspend/react/components/AnySpend.js +3 -0
  19. package/dist/esm/anyspend/react/components/AnySpendCustom.js +3 -0
  20. package/dist/esm/anyspend/react/components/common/CryptoPaymentMethod.js +175 -45
  21. package/dist/esm/anyspend/react/hooks/useAnyspendFlow.js +3 -0
  22. package/dist/esm/anyspend/react/hooks/useAutoSetActiveWalletFromWagmi.d.ts +10 -0
  23. package/dist/esm/anyspend/react/hooks/useAutoSetActiveWalletFromWagmi.js +70 -0
  24. package/dist/esm/global-account/react/components/SignInWithB3/SignInWithB3Flow.js +57 -12
  25. package/dist/esm/global-account/react/hooks/index.d.ts +1 -0
  26. package/dist/esm/global-account/react/hooks/index.js +1 -0
  27. package/dist/esm/global-account/react/hooks/useAuth.d.ts +76 -0
  28. package/dist/esm/global-account/react/hooks/useAuth.js +332 -0
  29. package/dist/esm/global-account/react/hooks/useAuthentication.d.ts +2 -2
  30. package/dist/esm/global-account/react/hooks/useAuthentication.js +72 -63
  31. package/dist/esm/global-account/react/hooks/useTWAuth.d.ts +3 -0
  32. package/dist/esm/global-account/react/hooks/useTWAuth.js +8 -0
  33. package/dist/esm/global-account/react/hooks/useTurnkeyAuth.js +54 -24
  34. package/dist/esm/global-account/react/hooks/useUserQuery.d.ts +1 -1
  35. package/dist/styles/index.css +1 -1
  36. package/dist/types/anyspend/react/hooks/useAutoSetActiveWalletFromWagmi.d.ts +10 -0
  37. package/dist/types/global-account/react/hooks/index.d.ts +1 -0
  38. package/dist/types/global-account/react/hooks/useAuth.d.ts +76 -0
  39. package/dist/types/global-account/react/hooks/useAuthentication.d.ts +2 -2
  40. package/dist/types/global-account/react/hooks/useTWAuth.d.ts +3 -0
  41. package/dist/types/global-account/react/hooks/useUserQuery.d.ts +1 -1
  42. package/package.json +1 -1
  43. package/src/anyspend/react/components/AnySpend.tsx +4 -0
  44. package/src/anyspend/react/components/AnySpendCustom.tsx +4 -0
  45. package/src/anyspend/react/components/common/CryptoPaymentMethod.tsx +253 -22
  46. package/src/anyspend/react/hooks/useAnyspendFlow.ts +4 -0
  47. package/src/anyspend/react/hooks/useAutoSetActiveWalletFromWagmi.ts +80 -0
  48. package/src/global-account/react/components/SignInWithB3/SignInWithB3Flow.tsx +77 -22
  49. package/src/global-account/react/hooks/index.ts +1 -0
  50. package/src/global-account/react/hooks/useAuth.ts +380 -0
  51. package/src/global-account/react/hooks/useAuthentication.ts +88 -85
  52. package/src/global-account/react/hooks/useTWAuth.tsx +10 -0
  53. package/src/global-account/react/hooks/useTurnkeyAuth.ts +59 -26
@@ -3,6 +3,7 @@ import { Loading, useAuthStore, useB3, useGetAllTWSigners, useModalStore, } from
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";
@@ -20,7 +21,9 @@ export function SignInWithB3Flow({ strategies, onLoginSuccess, onSessionKeySucce
20
21
  const account = useActiveAccount();
21
22
  const isAuthenticating = useAuthStore(state => state.isAuthenticating);
22
23
  const isAuthenticated = useAuthStore(state => state.isAuthenticated);
24
+ const setIsAuthenticated = useAuthStore(state => state.setIsAuthenticated);
23
25
  const isConnected = useAuthStore(state => state.isConnected);
26
+ const setIsConnected = useAuthStore(state => state.setIsConnected);
24
27
  const setJustCompletedLogin = useAuthStore(state => state.setJustCompletedLogin);
25
28
  const [refetchCount, setRefetchCount] = useState(0);
26
29
  const [refetchError, setRefetchError] = useState(null);
@@ -122,6 +125,10 @@ export function SignInWithB3Flow({ strategies, onLoginSuccess, onSessionKeySucce
122
125
  debug("Refetching user after Turnkey success...");
123
126
  await refetchUser();
124
127
  debug("User refetched successfully");
128
+ // Set authentication and connection state so UI updates properly
129
+ setIsAuthenticated(true);
130
+ setIsConnected(true);
131
+ setJustCompletedLogin(true);
125
132
  // After user data is refreshed, close Turnkey modal and go back to sign-in flow
126
133
  debug("Switching back to signInWithB3 modal");
127
134
  setB3ModalContentType({
@@ -151,6 +158,9 @@ export function SignInWithB3Flow({ strategies, onLoginSuccess, onSessionKeySucce
151
158
  closeAfterLogin,
152
159
  source,
153
160
  signersEnabled,
161
+ setIsAuthenticated,
162
+ setIsConnected,
163
+ setJustCompletedLogin,
154
164
  ]);
155
165
  // Handle post-login flow after signers are loaded
156
166
  useEffect(() => {
@@ -286,21 +296,56 @@ export function SignInWithB3Flow({ strategies, onLoginSuccess, onSessionKeySucce
286
296
  if (refetchError) {
287
297
  content = (_jsx(LoginStepContainer, { partnerId: partnerId, children: _jsx("div", { className: "p-4 text-center text-red-500", children: refetchError }) }));
288
298
  }
289
- else if (isAuthenticating || (isFetchingSigners && step === "login") || source === "requestPermissions") {
290
- 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" }) }) }));
291
- }
292
299
  else if (step === "login") {
293
- // Custom strategy
294
- if (strategies?.[0] === "privy") {
295
- content = _jsx(SignInWithB3Privy, { onSuccess: handleLoginSuccess, chain: chain });
296
- }
297
- else if (strategies) {
298
- // Strategies are explicitly provided
299
- content = (_jsx(LoginStepCustom, { strategies: strategies, chain: chain, onSuccess: handleLoginSuccess, onError: onError, automaticallySetFirstEoa: !!automaticallySetFirstEoa }));
300
+ // PRIORITY: If Turnkey is enabled, show Turnkey modal FIRST as the primary authentication option
301
+ // Show Turnkey when enabled and not already completed in this session
302
+ const shouldShowTurnkeyFirst = enableTurnkey && !turnkeyAuthCompleted;
303
+ if (shouldShowTurnkeyFirst) {
304
+ // Don't show loading spinner for Turnkey - let the modal handle its own loading state
305
+ // This prevents the infinite loop where isAuthenticating causes the modal to be replaced
306
+ debug("Showing Turnkey as primary authentication option", {
307
+ enableTurnkey,
308
+ turnkeyAuthCompleted,
309
+ isAuthenticated,
310
+ });
311
+ // Show Turnkey authentication as primary option
312
+ content = (_jsx(LoginStepContainer, { partnerId: partnerId, children: _jsx(TurnkeyAuthModal, { onSuccess: async (authenticatedUser) => {
313
+ debug("Turnkey authentication successful in primary flow", { authenticatedUser });
314
+ setTurnkeyAuthCompleted(true);
315
+ // After Turnkey auth, refetch user to get the full user object
316
+ await refetchUser();
317
+ // User is now authenticated via Turnkey
318
+ // Set both isAuthenticated and isConnected to true so UI updates properly
319
+ // Wallet connection is optional and can happen later for signing transactions
320
+ setIsAuthenticated(true);
321
+ setIsConnected(true);
322
+ setJustCompletedLogin(true);
323
+ // Call the login success callback
324
+ onLoginSuccess?.({});
325
+ }, onClose: () => {
326
+ // If user closes Turnkey modal, they can still use wallet connection as fallback
327
+ setTurnkeyAuthCompleted(true);
328
+ }, initialEmail: "", skipToOtp: false }) }));
300
329
  }
301
330
  else {
302
- // Default to handle all strategies we support
303
- content = _jsx(LoginStep, { chain: chain, onSuccess: handleLoginSuccess, onError: onError });
331
+ // Show loading spinner only if not in Turnkey flow
332
+ if (isAuthenticating || (isFetchingSigners && step === "login") || source === "requestPermissions") {
333
+ 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" }) }) }));
334
+ }
335
+ else {
336
+ // Custom strategy
337
+ if (strategies?.[0] === "privy") {
338
+ content = _jsx(SignInWithB3Privy, { onSuccess: handleLoginSuccess, chain: chain });
339
+ }
340
+ else if (strategies) {
341
+ // Strategies are explicitly provided
342
+ content = (_jsx(LoginStepCustom, { strategies: strategies, chain: chain, onSuccess: handleLoginSuccess, onError: onError, automaticallySetFirstEoa: !!automaticallySetFirstEoa }));
343
+ }
344
+ else {
345
+ // Default to handle all strategies we support
346
+ content = _jsx(LoginStep, { chain: chain, onSuccess: handleLoginSuccess, onError: onError });
347
+ }
348
+ }
304
349
  }
305
350
  }
306
351
  return content;
@@ -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
+ telNumber?: string | undefined;
25
+ username?: 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
+ phone?: string | undefined;
53
+ username?: 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
+ }
@@ -41,8 +41,8 @@ export declare function useAuthentication(partnerId: string): {
41
41
  name?: string | undefined;
42
42
  address?: string | undefined;
43
43
  email?: string | undefined;
44
- username?: string | undefined;
45
44
  phone?: string | undefined;
45
+ username?: string | undefined;
46
46
  fid?: string | undefined;
47
47
  };
48
48
  }[] | undefined;
@@ -63,6 +63,6 @@ export declare function useAuthentication(partnerId: string): {
63
63
  turnkeyOtpId?: string | undefined;
64
64
  };
65
65
  } | undefined;
66
- refetchUser: (wallet?: Wallet) => Promise<import("@feathersjs/authentication").AuthenticationResult>;
66
+ refetchUser: () => Promise<import("@feathersjs/authentication").AuthenticationResult>;
67
67
  setUser: (newUser?: import("@b3dotfun/b3-api").Users) => void;
68
68
  };