@b3dotfun/sdk 0.0.83-test.0 → 0.0.83

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 (68) hide show
  1. package/dist/cjs/anyspend/react/components/AnySpend.js +0 -3
  2. package/dist/cjs/anyspend/react/components/AnySpendCollectorClubPurchase.js +1 -1
  3. package/dist/cjs/anyspend/react/components/AnySpendCustom.js +0 -3
  4. package/dist/cjs/anyspend/react/components/common/CryptoPaymentMethod.js +47 -177
  5. package/dist/cjs/anyspend/react/hooks/useAnyspendFlow.js +0 -3
  6. package/dist/cjs/anyspend/utils/chain.d.ts +38 -0
  7. package/dist/cjs/anyspend/utils/chain.js +22 -1
  8. package/dist/cjs/anyspend/utils/token.d.ts +3 -0
  9. package/dist/cjs/anyspend/utils/token.js +17 -1
  10. package/dist/cjs/global-account/react/components/SignInWithB3/SignInWithB3Flow.js +12 -57
  11. package/dist/cjs/global-account/react/hooks/index.d.ts +0 -1
  12. package/dist/cjs/global-account/react/hooks/index.js +1 -3
  13. package/dist/cjs/global-account/react/hooks/useAuthentication.d.ts +2 -2
  14. package/dist/cjs/global-account/react/hooks/useAuthentication.js +63 -72
  15. package/dist/cjs/global-account/react/hooks/useTWAuth.d.ts +0 -3
  16. package/dist/cjs/global-account/react/hooks/useTWAuth.js +0 -8
  17. package/dist/cjs/global-account/react/hooks/useTurnkeyAuth.js +24 -54
  18. package/dist/cjs/global-account/react/hooks/useUserQuery.d.ts +1 -1
  19. package/dist/esm/anyspend/react/components/AnySpend.js +0 -3
  20. package/dist/esm/anyspend/react/components/AnySpendCollectorClubPurchase.js +1 -1
  21. package/dist/esm/anyspend/react/components/AnySpendCustom.js +0 -3
  22. package/dist/esm/anyspend/react/components/common/CryptoPaymentMethod.js +45 -175
  23. package/dist/esm/anyspend/react/hooks/useAnyspendFlow.js +0 -3
  24. package/dist/esm/anyspend/utils/chain.d.ts +38 -0
  25. package/dist/esm/anyspend/utils/chain.js +22 -1
  26. package/dist/esm/anyspend/utils/token.d.ts +3 -0
  27. package/dist/esm/anyspend/utils/token.js +15 -1
  28. package/dist/esm/global-account/react/components/SignInWithB3/SignInWithB3Flow.js +12 -57
  29. package/dist/esm/global-account/react/hooks/index.d.ts +0 -1
  30. package/dist/esm/global-account/react/hooks/index.js +0 -1
  31. package/dist/esm/global-account/react/hooks/useAuthentication.d.ts +2 -2
  32. package/dist/esm/global-account/react/hooks/useAuthentication.js +63 -72
  33. package/dist/esm/global-account/react/hooks/useTWAuth.d.ts +0 -3
  34. package/dist/esm/global-account/react/hooks/useTWAuth.js +0 -8
  35. package/dist/esm/global-account/react/hooks/useTurnkeyAuth.js +24 -54
  36. package/dist/esm/global-account/react/hooks/useUserQuery.d.ts +1 -1
  37. package/dist/styles/index.css +1 -1
  38. package/dist/types/anyspend/utils/chain.d.ts +38 -0
  39. package/dist/types/anyspend/utils/token.d.ts +3 -0
  40. package/dist/types/global-account/react/hooks/index.d.ts +0 -1
  41. package/dist/types/global-account/react/hooks/useAuthentication.d.ts +2 -2
  42. package/dist/types/global-account/react/hooks/useTWAuth.d.ts +0 -3
  43. package/dist/types/global-account/react/hooks/useUserQuery.d.ts +1 -1
  44. package/package.json +1 -1
  45. package/src/anyspend/react/components/AnySpend.tsx +0 -4
  46. package/src/anyspend/react/components/AnySpendCollectorClubPurchase.tsx +1 -1
  47. package/src/anyspend/react/components/AnySpendCustom.tsx +0 -4
  48. package/src/anyspend/react/components/common/CryptoPaymentMethod.tsx +22 -253
  49. package/src/anyspend/react/hooks/useAnyspendFlow.ts +0 -4
  50. package/src/anyspend/utils/chain.ts +31 -1
  51. package/src/anyspend/utils/token.ts +17 -1
  52. package/src/global-account/react/components/SignInWithB3/SignInWithB3Flow.tsx +22 -77
  53. package/src/global-account/react/hooks/index.ts +0 -1
  54. package/src/global-account/react/hooks/useAuthentication.ts +85 -88
  55. package/src/global-account/react/hooks/useTWAuth.tsx +0 -10
  56. package/src/global-account/react/hooks/useTurnkeyAuth.ts +26 -59
  57. package/dist/cjs/anyspend/react/hooks/useAutoSetActiveWalletFromWagmi.d.ts +0 -10
  58. package/dist/cjs/anyspend/react/hooks/useAutoSetActiveWalletFromWagmi.js +0 -73
  59. package/dist/cjs/global-account/react/hooks/useAuth.d.ts +0 -76
  60. package/dist/cjs/global-account/react/hooks/useAuth.js +0 -338
  61. package/dist/esm/anyspend/react/hooks/useAutoSetActiveWalletFromWagmi.d.ts +0 -10
  62. package/dist/esm/anyspend/react/hooks/useAutoSetActiveWalletFromWagmi.js +0 -70
  63. package/dist/esm/global-account/react/hooks/useAuth.d.ts +0 -76
  64. package/dist/esm/global-account/react/hooks/useAuth.js +0 -332
  65. package/dist/types/anyspend/react/hooks/useAutoSetActiveWalletFromWagmi.d.ts +0 -10
  66. package/dist/types/global-account/react/hooks/useAuth.d.ts +0 -76
  67. package/src/anyspend/react/hooks/useAutoSetActiveWalletFromWagmi.ts +0 -80
  68. package/src/global-account/react/hooks/useAuth.ts +0 -380
@@ -1,332 +0,0 @@
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,10 +0,0 @@
1
- /**
2
- * Hook that automatically sets the active thirdweb wallet when a wagmi wallet connects.
3
- *
4
- * This is useful for syncing wagmi wallet connections with thirdweb's wallet system,
5
- * ensuring that when users connect via wagmi, the active wallet is properly set.
6
- *
7
- * Place this hook in components that stay mounted throughout the user flow
8
- * (not in components that unmount during navigation).
9
- */
10
- export declare function useAutoSetActiveWalletFromWagmi(): void;
@@ -1,76 +0,0 @@
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
- };
@@ -1,80 +0,0 @@
1
- import { client } from "@b3dotfun/sdk/shared/utils/thirdweb";
2
- import { useCallback, useEffect, useRef } from "react";
3
- import { useSetActiveWallet } from "thirdweb/react";
4
- import { WalletId, createWallet } from "thirdweb/wallets";
5
- import { useAccount } from "wagmi";
6
-
7
- /**
8
- * Hook that automatically sets the active thirdweb wallet when a wagmi wallet connects.
9
- *
10
- * This is useful for syncing wagmi wallet connections with thirdweb's wallet system,
11
- * ensuring that when users connect via wagmi, the active wallet is properly set.
12
- *
13
- * Place this hook in components that stay mounted throughout the user flow
14
- * (not in components that unmount during navigation).
15
- */
16
- export function useAutoSetActiveWalletFromWagmi() {
17
- const { address: wagmiAddress, connector: wagmiConnector } = useAccount();
18
- const setActiveWallet = useSetActiveWallet();
19
- const prevWagmiAddress = useRef<string | undefined>(undefined);
20
-
21
- // Map wagmi connector names to thirdweb wallet IDs
22
- const getThirdwebWalletId = useCallback((connectorName: string): WalletId | null => {
23
- const walletMap: Record<string, WalletId> = {
24
- MetaMask: "io.metamask",
25
- "Coinbase Wallet": "com.coinbase.wallet",
26
- Rainbow: "me.rainbow",
27
- WalletConnect: "walletConnect",
28
- Phantom: "app.phantom",
29
- };
30
- return walletMap[connectorName] || null;
31
- }, []);
32
-
33
- // Create thirdweb wallet from wagmi connector
34
- const createThirdwebWalletFromConnector = useCallback(
35
- async (connectorName: string) => {
36
- const walletId = getThirdwebWalletId(connectorName);
37
- if (!walletId) {
38
- console.warn(`No thirdweb wallet ID found for connector: ${connectorName}`);
39
- return null;
40
- }
41
-
42
- try {
43
- const thirdwebWallet = createWallet(walletId);
44
- await thirdwebWallet.connect({ client });
45
- return thirdwebWallet;
46
- } catch (error) {
47
- console.error(`Failed to create thirdweb wallet for ${connectorName}:`, error);
48
- return null;
49
- }
50
- },
51
- [getThirdwebWalletId],
52
- );
53
-
54
- // Listen for wagmi wallet connections and automatically set active wallet
55
- useEffect(() => {
56
- const isNewConnection = wagmiAddress && wagmiAddress !== prevWagmiAddress.current;
57
-
58
- if (isNewConnection && wagmiConnector?.name) {
59
- prevWagmiAddress.current = wagmiAddress;
60
-
61
- const setupThirdwebWallet = async () => {
62
- try {
63
- const thirdwebWallet = await createThirdwebWalletFromConnector(wagmiConnector.name);
64
- if (thirdwebWallet) {
65
- setActiveWallet(thirdwebWallet);
66
- console.log(`Auto-set active wallet for ${wagmiConnector.name}`);
67
- }
68
- } catch (error) {
69
- console.error("Failed to auto-set active wallet:", error);
70
- }
71
- };
72
-
73
- setupThirdwebWallet();
74
- }
75
-
76
- if (!wagmiAddress) {
77
- prevWagmiAddress.current = undefined;
78
- }
79
- }, [wagmiAddress, wagmiConnector?.name, setActiveWallet, createThirdwebWalletFromConnector]);
80
- }