@b3dotfun/sdk 0.0.81 → 0.0.82-alpha.1

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.
@@ -4,13 +4,9 @@ import { toast, useAccountWallet, WalletImage } from "../../../../global-account
4
4
  import { cn } from "../../../../shared/utils/cn.js";
5
5
  import { shortenAddress } from "../../../../shared/utils/formatAddress.js";
6
6
  import { client } from "../../../../shared/utils/thirdweb.js";
7
- import { WalletCoinbase, WalletMetamask, WalletRainbow, WalletWalletConnect } from "@web3icons/react";
8
7
  import { ChevronLeft, ChevronRightCircle, Wallet, X, ZapIcon } from "lucide-react";
9
- import { useState } from "react";
10
- import { createPortal } from "react-dom";
11
- import { useSetActiveWallet, useWalletInfo } from "thirdweb/react";
12
- import { createWallet } from "thirdweb/wallets";
13
- import { useAccount, useConnect, useDisconnect, useWalletClient } from "wagmi";
8
+ import { useConnectModal, useSetActiveWallet, useWalletInfo } from "thirdweb/react";
9
+ import { useAccount, useDisconnect } from "wagmi";
14
10
  import { useConnectedWalletDisplay } from "../../hooks/useConnectedWalletDisplay.js";
15
11
  export var CryptoPaymentMethodType;
16
12
  (function (CryptoPaymentMethodType) {
@@ -22,193 +18,80 @@ export var CryptoPaymentMethodType;
22
18
  export function CryptoPaymentMethod({ selectedPaymentMethod, setSelectedPaymentMethod, isCreatingOrder, onBack, onSelectPaymentMethod, }) {
23
19
  const { connectedEOAWallet: connectedEOAWallet, connectedSmartWallet: connectedSmartWallet } = useAccountWallet();
24
20
  const { connector, address } = useAccount();
25
- const { connect, connectors, isPending } = useConnect();
26
21
  const { disconnect } = useDisconnect();
27
- const { data: walletClient } = useWalletClient();
28
- const [showWalletModal, setShowWalletModal] = useState(false);
22
+ const { connect: openConnectModal } = useConnectModal();
29
23
  const setActiveWallet = useSetActiveWallet();
30
24
  const { data: eoaWalletInfo } = useWalletInfo(connectedEOAWallet?.id);
31
- const isConnected = !!connectedEOAWallet;
32
25
  const globalAddress = connectedSmartWallet?.getAccount()?.address;
33
26
  // Use custom hook to determine wallet display logic
34
27
  const { shouldShowConnectedEOA, shouldShowWagmiWallet } = useConnectedWalletDisplay(selectedPaymentMethod);
35
- console.log("shouldShowWagmiWallet :", shouldShowWagmiWallet);
36
- // Map wagmi connector names to thirdweb wallet IDs
37
- const getThirdwebWalletId = (connectorName) => {
38
- const walletMap = {
39
- MetaMask: "io.metamask",
40
- "Coinbase Wallet": "com.coinbase.wallet",
41
- Rainbow: "me.rainbow",
42
- WalletConnect: "walletConnect",
43
- Phantom: "app.phantom",
44
- };
45
- return walletMap[connectorName] || null;
46
- };
47
- // Create thirdweb wallet from wagmi connector
48
- const createThirdwebWalletFromConnector = async (connectorName) => {
49
- const walletId = getThirdwebWalletId(connectorName);
50
- if (!walletId) {
51
- console.warn(`No thirdweb wallet ID found for connector: ${connectorName}`);
52
- return null;
53
- }
28
+ // Handle wallet connection using thirdweb modal
29
+ const handleConnectWallet = async () => {
54
30
  try {
55
- const thirdwebWallet = createWallet(walletId);
56
- // Connect the wallet to sync with the existing wagmi connection
57
- await thirdwebWallet.connect({ client });
58
- return thirdwebWallet;
59
- }
60
- catch (error) {
61
- console.error(`Failed to create thirdweb wallet for ${connectorName}:`, error);
62
- return null;
63
- }
64
- };
65
- // Define available wallet connectors
66
- const availableConnectors = connectors.filter(connector => ["MetaMask", "WalletConnect", "Coinbase Wallet", "Rainbow", "Phantom"].includes(connector.name));
67
- // Define wallet options with icons and info
68
- const walletOptions = [
69
- {
70
- id: "metamask",
71
- name: "MetaMask",
72
- icon: _jsx(WalletMetamask, { size: 48 }),
73
- description: "Connect using MetaMask browser extension",
74
- connector: availableConnectors.find(c => c.name === "MetaMask"),
75
- },
76
- {
77
- id: "coinbase",
78
- name: "Coinbase Wallet",
79
- icon: _jsx(WalletCoinbase, { size: 48 }),
80
- description: "Connect using Coinbase Wallet",
81
- connector: availableConnectors.find(c => c.name === "Coinbase Wallet"),
82
- },
83
- {
84
- id: "rainbow",
85
- name: "Rainbow",
86
- icon: _jsx(WalletRainbow, { size: 48 }),
87
- description: "Connect using Rainbow wallet",
88
- connector: availableConnectors.find(c => c.name === "Rainbow"),
89
- },
90
- {
91
- id: "walletconnect",
92
- name: "WalletConnect",
93
- icon: _jsx(WalletWalletConnect, { size: 48 }),
94
- description: "Connect using WalletConnect protocol",
95
- connector: availableConnectors.find(c => c.name === "WalletConnect"),
96
- },
97
- ].filter(wallet => wallet.connector); // Only show wallets that have available connectors
98
- // Reset modal state when closing
99
- const handleCloseModal = () => {
100
- setShowWalletModal(false);
101
- };
102
- // Function to request wallet permissions for specific wallet
103
- const requestWalletPermissions = async (walletConnector) => {
104
- try {
105
- // If a specific wallet connector is provided and it's different from current
106
- if (walletConnector && connector?.name !== walletConnector.name) {
107
- // Disconnect current and connect to the selected wallet
108
- // if (isConnected) {
109
- // disconnect();
110
- // // Small delay to ensure disconnection
111
- // await new Promise(resolve => setTimeout(resolve, 100));
112
- // }
113
- await connect({ connector: walletConnector });
114
- setSelectedPaymentMethod(CryptoPaymentMethodType.CONNECT_WALLET);
115
- onSelectPaymentMethod(CryptoPaymentMethodType.CONNECT_WALLET);
116
- toast.success(`Connected to ${walletConnector.name}`);
117
- return;
118
- }
119
- // If same wallet or no specific wallet, request permissions for account switching
120
- if (walletClient && "request" in walletClient) {
121
- await walletClient.request({
122
- method: "wallet_requestPermissions",
123
- params: [{ eth_accounts: {} }],
124
- });
125
- toast.success("Account selection completed");
31
+ const wallet = await openConnectModal({ client, setActive: false });
32
+ if (wallet) {
33
+ // setActiveWallet(wallet);
126
34
  setSelectedPaymentMethod(CryptoPaymentMethodType.CONNECT_WALLET);
127
35
  onSelectPaymentMethod(CryptoPaymentMethodType.CONNECT_WALLET);
128
- }
129
- else {
130
- // Fallback: show modal for manual wallet selection
131
- setShowWalletModal(true);
36
+ toast.success("Wallet connected");
132
37
  }
133
38
  }
134
39
  catch (error) {
135
- console.error("Failed to request wallet permissions:", error);
40
+ console.error("Failed to connect wallet:", error);
136
41
  if (error && typeof error === "object" && "message" in error) {
137
42
  const errorMessage = error.message.toLowerCase();
138
43
  if (errorMessage.includes("rejected") ||
139
44
  errorMessage.includes("denied") ||
140
45
  errorMessage.includes("cancelled")) {
141
- toast.error("Account selection cancelled");
46
+ // User cancelled - no toast needed
142
47
  }
143
48
  else {
144
- toast.error("Failed to open account selection");
49
+ toast.error("Failed to connect wallet");
145
50
  }
146
51
  }
147
- else {
148
- toast.error("Failed to open account selection");
149
- }
150
52
  }
151
53
  };
152
- return (_jsxs("div", { className: "crypto-payment-method mx-auto h-fit w-[460px] max-w-full px-5 pb-5 pt-5 sm:px-0 sm:pt-5", children: [_jsxs("div", { className: cn("relative flex flex-col gap-10"), children: [_jsx("button", { onClick: onBack, className: "text-as-quaternary hover:text-as-primary absolute flex h-8 w-8 items-center justify-center rounded-lg transition-colors", children: _jsx(ChevronLeft, { className: "h-6 w-6" }) }), _jsx("div", { className: "flex items-center justify-around gap-4", children: _jsx("div", { className: "flex-1 text-center", children: _jsx("h2", { className: "text-as-primary text-lg font-semibold", children: "Select a payment method" }) }) }), process.env.NODE_ENV === "development" && (_jsxs("div", { className: "rounded-lg border border-yellow-500/50 bg-yellow-50 p-3 dark:bg-yellow-950/20", children: [_jsx("p", { className: "mb-2 text-xs font-semibold text-yellow-800 dark:text-yellow-300", children: "\uD83E\uDDEA Toast Test (Dev Only)" }), _jsxs("div", { className: "flex flex-wrap gap-2", children: [_jsx("button", { onClick: () => toast.success("Success! Transaction completed"), className: "rounded bg-green-600 px-2 py-1 text-xs font-medium text-white hover:bg-green-700", children: "Success" }), _jsx("button", { onClick: () => toast.error("Error! Transaction failed"), className: "rounded bg-red-600 px-2 py-1 text-xs font-medium text-white hover:bg-red-700", children: "Error" }), _jsx("button", { onClick: () => toast.info("Info: Processing your request..."), className: "rounded bg-blue-600 px-2 py-1 text-xs font-medium text-white hover:bg-blue-700", children: "Info" }), _jsx("button", { onClick: () => toast.warning("Warning: Low balance detected"), className: "rounded bg-yellow-600 px-2 py-1 text-xs font-medium text-white hover:bg-yellow-700", children: "Warning" }), _jsx("button", { onClick: () => {
153
- toast.success("Multiple test 1");
154
- setTimeout(() => toast.info("Multiple test 2"), 200);
155
- setTimeout(() => toast.warning("Multiple test 3"), 400);
156
- }, className: "rounded bg-purple-600 px-2 py-1 text-xs font-medium text-white hover:bg-purple-700", children: "Multiple" })] })] })), _jsxs("div", { className: "crypto-payment-methods flex flex-col gap-4", children: [(shouldShowConnectedEOA || shouldShowWagmiWallet || globalAddress) && (_jsxs("div", { className: "installed-wallets", children: [_jsx("h3", { className: "text-as-primary/80 mb-3 text-sm font-medium", children: "Connected wallets" }), _jsxs("div", { className: "space-y-2", children: [shouldShowConnectedEOA && (_jsx("button", { onClick: () => {
157
- setSelectedPaymentMethod(CryptoPaymentMethodType.CONNECT_WALLET);
158
- onSelectPaymentMethod(CryptoPaymentMethodType.CONNECT_WALLET);
159
- if (connectedEOAWallet) {
160
- setActiveWallet(connectedEOAWallet);
161
- }
162
- toast.success(`Selected ${eoaWalletInfo?.name || connector?.name || "wallet"}`);
163
- }, className: cn("crypto-payment-method-connect-wallet eoa-wallet w-full rounded-xl border p-4 text-left transition-all hover:shadow-md", selectedPaymentMethod === CryptoPaymentMethodType.CONNECT_WALLET
164
- ? "connected-wallet border-as-brand bg-as-brand/5"
165
- : "border-as-border-secondary bg-as-surface-primary hover:border-as-secondary/80"), children: _jsxs("div", { className: "flex items-center justify-between", children: [_jsxs("div", { className: "flex items-center gap-3", children: [_jsx("div", { className: "wallet-icon flex h-10 w-10 items-center justify-center rounded-full bg-blue-100", children: _jsx(Wallet, { className: "h-5 w-5 text-blue-600" }) }), _jsxs("div", { className: "flex flex-col", children: [_jsx("span", { className: "text-as-primary font-semibold", children: eoaWalletInfo?.name || connector?.name || "Connected Wallet" }), _jsx("span", { className: "text-as-primary/60 text-sm", children: shortenAddress(connectedEOAWallet?.getAccount()?.address || "") })] })] }), _jsxs("div", { className: "flex items-center gap-2", children: [selectedPaymentMethod === CryptoPaymentMethodType.CONNECT_WALLET && (_jsx("div", { className: "h-2 w-2 rounded-full bg-green-500" })), _jsx("button", { onClick: e => {
166
- e.stopPropagation();
167
- disconnect();
168
- toast.success("Wallet disconnected");
169
- if (selectedPaymentMethod === CryptoPaymentMethodType.CONNECT_WALLET) {
170
- setSelectedPaymentMethod(CryptoPaymentMethodType.NONE);
171
- }
172
- }, className: "text-as-primary/60 hover:text-as-primary/80 rounded-lg p-1.5 transition-colors", children: _jsx(X, { className: "h-4 w-4" }) })] })] }) })), shouldShowWagmiWallet && (_jsx("button", { onClick: async () => {
173
- setSelectedPaymentMethod(CryptoPaymentMethodType.CONNECT_WALLET);
174
- onSelectPaymentMethod(CryptoPaymentMethodType.CONNECT_WALLET);
175
- // Create thirdweb wallet from wagmi connector
176
- if (connector?.name) {
177
- const thirdwebWallet = await createThirdwebWalletFromConnector(connector.name);
178
- if (thirdwebWallet) {
179
- setActiveWallet(thirdwebWallet);
180
- }
181
- }
182
- toast.success(`Selected ${connector?.name || "wallet"}`);
183
- }, className: cn("crypto-payment-method-connect-wallet wagmi-wallet w-full rounded-xl border p-4 text-left transition-all hover:shadow-md", selectedPaymentMethod === CryptoPaymentMethodType.CONNECT_WALLET
184
- ? "connected-wallet border-as-brand bg-as-brand/5"
185
- : "border-as-border-secondary bg-as-surface-primary hover:border-as-secondary/80"), children: _jsxs("div", { className: "flex items-center justify-between", children: [_jsxs("div", { className: "flex items-center gap-3", children: [_jsx("div", { className: "wallet-icon flex h-10 w-10 items-center justify-center rounded-full bg-blue-100", children: _jsx(Wallet, { className: "h-5 w-5 text-blue-600" }) }), _jsxs("div", { className: "flex flex-col", children: [_jsx("span", { className: "text-as-primary font-semibold", children: connector?.name || "Connected Wallet" }), _jsx("span", { className: "text-as-primary/60 text-sm", children: shortenAddress(address || "") })] })] }), _jsxs("div", { className: "flex items-center gap-2", children: [selectedPaymentMethod === CryptoPaymentMethodType.CONNECT_WALLET && (_jsx("div", { className: "h-2 w-2 rounded-full bg-green-500" })), _jsx("button", { onClick: e => {
186
- e.stopPropagation();
187
- disconnect();
188
- toast.success("Wallet disconnected");
189
- if (selectedPaymentMethod === CryptoPaymentMethodType.CONNECT_WALLET) {
190
- setSelectedPaymentMethod(CryptoPaymentMethodType.NONE);
191
- }
192
- }, className: "text-as-primary/60 hover:text-as-primary/80 rounded-lg p-1.5 transition-colors", children: _jsx(X, { className: "h-4 w-4" }) })] })] }) })), globalAddress && (_jsx("button", { onClick: () => {
193
- setSelectedPaymentMethod(CryptoPaymentMethodType.GLOBAL_WALLET);
194
- onSelectPaymentMethod(CryptoPaymentMethodType.GLOBAL_WALLET);
195
- toast.success("Selected B3 Account");
196
- }, className: cn("crypto-payment-method-global-wallet w-full rounded-xl border p-4 text-left transition-all hover:shadow-md", selectedPaymentMethod === CryptoPaymentMethodType.GLOBAL_WALLET
197
- ? "connected-wallet border-as-brand bg-as-brand/5"
198
- : "border-as-border-secondary bg-as-surface-primary hover:border-as-secondary/80"), children: _jsxs("div", { className: "flex items-center justify-between", children: [_jsxs("div", { className: "flex items-center gap-3", children: [_jsx(WalletImage, { fallback: _jsx("div", { className: "wallet-icon flex h-10 w-10 items-center justify-center rounded-full bg-purple-100", children: _jsx(Wallet, { className: "h-5 w-5 text-purple-600" }) }) }), _jsxs("div", { className: "flex flex-col", children: [_jsx("span", { className: "text-as-primary font-semibold", children: "Global Account" }), _jsx("span", { className: "text-as-primary/60 text-sm", children: shortenAddress(globalAddress || "") })] })] }), _jsx("div", { className: "flex items-center gap-2", children: selectedPaymentMethod === CryptoPaymentMethodType.GLOBAL_WALLET && (_jsx("div", { className: "h-2 w-2 rounded-full bg-green-500" })) })] }) }))] })] })), _jsxs("div", { className: "other-payment-methods", children: [_jsx("h3", { className: "text-as-primary/80 mb-3 text-sm font-medium", children: "Payment methods" }), _jsxs("div", { className: "space-y-3", children: [_jsxs("button", { onClick: () => {
199
- // Always show wallet selection modal first
200
- setShowWalletModal(true);
201
- }, className: "crypto-payment-method-connect-wallet bg-as-surface-primary border-as-border-secondary hover:border-as-secondary/80 group flex w-full items-center justify-between gap-4 rounded-xl border px-4 py-3.5 transition-all duration-200 hover:shadow-md", children: [_jsxs("div", { className: "flex items-center gap-3", children: [_jsx("div", { className: "wallet-icon flex h-8 w-8 items-center justify-center rounded-full bg-blue-100", children: _jsx(Wallet, { className: "h-4 w-4 text-blue-600" }) }), _jsx("div", { className: "flex flex-col items-start text-left", children: _jsx("h4", { className: "text-as-primary font-semibold", children: "Connect wallet" }) })] }), _jsx(ChevronRightCircle, { className: "text-as-primary/40 group-hover:text-as-primary/60 h-5 w-5 transition-colors" })] }), _jsxs("button", { onClick: () => {
202
- setSelectedPaymentMethod(CryptoPaymentMethodType.TRANSFER_CRYPTO);
203
- onSelectPaymentMethod(CryptoPaymentMethodType.TRANSFER_CRYPTO);
204
- }, disabled: isCreatingOrder, className: "crypto-payment-method-transfer bg-as-surface-primary border-as-border-secondary hover:border-as-secondary/80 group flex w-full items-center justify-between gap-4 rounded-xl border px-4 py-3.5 transition-all duration-200 hover:shadow-md", children: [_jsxs("div", { className: "flex items-center gap-3", children: [_jsx("div", { className: "wallet-icon flex h-8 w-8 items-center justify-center rounded-full bg-orange-100", children: _jsx(ZapIcon, { className: "h-4 w-4" }) }), _jsx("div", { className: "flex flex-col items-start text-left", children: _jsx("h4", { className: "text-as-primary font-semibold", children: "Transfer crypto" }) })] }), _jsx(ChevronRightCircle, { className: "text-as-primary/40 group-hover:text-as-primary/60 h-5 w-5 transition-colors" })] })] })] })] })] }), showWalletModal &&
205
- createPortal(_jsx("div", { className: "wallet-connection-modal pointer-events-auto fixed inset-0 z-[9999] flex items-center justify-center bg-black/50", children: _jsxs("div", { className: "max-h-[80vh] w-[400px] max-w-[90vw] overflow-auto rounded-xl bg-white p-6 dark:bg-gray-900", children: [_jsxs("div", { className: "mb-4 flex items-center justify-between", children: [_jsx("h3", { className: "text-lg font-semibold text-gray-900 dark:text-white", children: isConnected ? "Switch wallet or account" : "Choose wallet to connect" }), _jsx("button", { onClick: handleCloseModal, className: "text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200", children: _jsx(X, { className: "h-5 w-5" }) })] }), _jsx("div", { className: "space-y-4", children: _jsx("div", { className: "space-y-3", children: walletOptions.map(walletOption => {
206
- const isCurrentWallet = isConnected && connector?.name === walletOption.connector?.name;
207
- return (_jsx("button", { onClick: async () => {
208
- handleCloseModal();
209
- await requestWalletPermissions(walletOption.connector);
210
- }, disabled: isPending, className: `wallet-option w-full rounded-xl border p-4 text-left transition-all hover:shadow-md disabled:opacity-50 ${isCurrentWallet
211
- ? "wallet-option--active border-blue-500 bg-blue-50 dark:bg-blue-900/20"
212
- : "border-gray-200 bg-white hover:border-gray-300 dark:border-gray-600 dark:bg-gray-800 dark:hover:border-gray-500"}`, children: _jsxs("div", { className: "flex items-center justify-between", children: [_jsxs("div", { className: "flex items-center gap-3", children: [walletOption.icon, _jsxs("div", { children: [_jsxs("div", { className: "wallet-option-name flex items-center gap-2", children: [_jsx("div", { className: "text-sm font-semibold text-gray-900 dark:text-white", children: walletOption.name }), isCurrentWallet && (_jsx("span", { className: "rounded-full bg-blue-100 px-2 py-0.5 text-xs font-medium text-blue-700 dark:bg-blue-800 dark:text-blue-200", children: "Connected" }))] }), _jsx("div", { className: "text-xs text-gray-500 dark:text-gray-400", children: isCurrentWallet ? "Switch account or reconnect" : walletOption.description })] })] }), _jsx(ChevronRightCircle, { className: "h-5 w-5 text-gray-400" })] }) }, walletOption.id));
213
- }) }) })] }) }), typeof window !== "undefined" ? document.getElementById("b3-root") || document.body : document.body)] }));
54
+ return (_jsx("div", { className: "crypto-payment-method mx-auto h-fit w-[460px] max-w-full px-5 pb-5 pt-5 sm:px-0 sm:pt-5", children: _jsxs("div", { className: cn("relative flex flex-col gap-10"), children: [_jsx("button", { onClick: onBack, className: "text-as-quaternary hover:text-as-primary absolute flex h-8 w-8 items-center justify-center rounded-lg transition-colors", children: _jsx(ChevronLeft, { className: "h-6 w-6" }) }), _jsx("div", { className: "flex items-center justify-around gap-4", children: _jsx("div", { className: "flex-1 text-center", children: _jsx("h2", { className: "text-as-primary text-lg font-semibold", children: "Select a payment method" }) }) }), process.env.NODE_ENV === "development" && (_jsxs("div", { className: "rounded-lg border border-yellow-500/50 bg-yellow-50 p-3 dark:bg-yellow-950/20", children: [_jsx("p", { className: "mb-2 text-xs font-semibold text-yellow-800 dark:text-yellow-300", children: "\uD83E\uDDEA Toast Test (Dev Only)" }), _jsxs("div", { className: "flex flex-wrap gap-2", children: [_jsx("button", { onClick: () => toast.success("Success! Transaction completed"), className: "rounded bg-green-600 px-2 py-1 text-xs font-medium text-white hover:bg-green-700", children: "Success" }), _jsx("button", { onClick: () => toast.error("Error! Transaction failed"), className: "rounded bg-red-600 px-2 py-1 text-xs font-medium text-white hover:bg-red-700", children: "Error" }), _jsx("button", { onClick: () => toast.info("Info: Processing your request..."), className: "rounded bg-blue-600 px-2 py-1 text-xs font-medium text-white hover:bg-blue-700", children: "Info" }), _jsx("button", { onClick: () => toast.warning("Warning: Low balance detected"), className: "rounded bg-yellow-600 px-2 py-1 text-xs font-medium text-white hover:bg-yellow-700", children: "Warning" }), _jsx("button", { onClick: () => {
55
+ toast.success("Multiple test 1");
56
+ setTimeout(() => toast.info("Multiple test 2"), 200);
57
+ setTimeout(() => toast.warning("Multiple test 3"), 400);
58
+ }, className: "rounded bg-purple-600 px-2 py-1 text-xs font-medium text-white hover:bg-purple-700", children: "Multiple" })] })] })), _jsxs("div", { className: "crypto-payment-methods flex flex-col gap-4", children: [(shouldShowConnectedEOA || shouldShowWagmiWallet || globalAddress) && (_jsxs("div", { className: "installed-wallets", children: [_jsx("h3", { className: "text-as-primary/80 mb-3 text-sm font-medium", children: "Connected wallets" }), _jsxs("div", { className: "space-y-2", children: [shouldShowConnectedEOA && (_jsx("button", { onClick: () => {
59
+ setSelectedPaymentMethod(CryptoPaymentMethodType.CONNECT_WALLET);
60
+ onSelectPaymentMethod(CryptoPaymentMethodType.CONNECT_WALLET);
61
+ if (connectedEOAWallet) {
62
+ setActiveWallet(connectedEOAWallet);
63
+ }
64
+ toast.success(`Selected ${eoaWalletInfo?.name || connector?.name || "wallet"}`);
65
+ }, className: cn("crypto-payment-method-connect-wallet eoa-wallet w-full rounded-xl border p-4 text-left transition-all hover:shadow-md", selectedPaymentMethod === CryptoPaymentMethodType.CONNECT_WALLET
66
+ ? "connected-wallet border-as-brand bg-as-brand/5"
67
+ : "border-as-border-secondary bg-as-surface-primary hover:border-as-secondary/80"), children: _jsxs("div", { className: "flex items-center justify-between", children: [_jsxs("div", { className: "flex items-center gap-3", children: [_jsx("div", { className: "wallet-icon flex h-10 w-10 items-center justify-center rounded-full bg-blue-100", children: _jsx(Wallet, { className: "h-5 w-5 text-blue-600" }) }), _jsxs("div", { className: "flex flex-col", children: [_jsx("span", { className: "text-as-primary font-semibold", children: eoaWalletInfo?.name || connector?.name || "Connected Wallet" }), _jsx("span", { className: "text-as-primary/60 text-sm", children: shortenAddress(connectedEOAWallet?.getAccount()?.address || "") })] })] }), _jsxs("div", { className: "flex items-center gap-2", children: [selectedPaymentMethod === CryptoPaymentMethodType.CONNECT_WALLET && (_jsx("div", { className: "h-2 w-2 rounded-full bg-green-500" })), _jsx("button", { onClick: e => {
68
+ e.stopPropagation();
69
+ disconnect();
70
+ toast.success("Wallet disconnected");
71
+ if (selectedPaymentMethod === CryptoPaymentMethodType.CONNECT_WALLET) {
72
+ setSelectedPaymentMethod(CryptoPaymentMethodType.NONE);
73
+ }
74
+ }, className: "text-as-primary/60 hover:text-as-primary/80 rounded-lg p-1.5 transition-colors", children: _jsx(X, { className: "h-4 w-4" }) })] })] }) })), shouldShowWagmiWallet && (_jsx("button", { onClick: () => {
75
+ setSelectedPaymentMethod(CryptoPaymentMethodType.CONNECT_WALLET);
76
+ onSelectPaymentMethod(CryptoPaymentMethodType.CONNECT_WALLET);
77
+ toast.success(`Selected ${connector?.name || "wallet"}`);
78
+ }, className: cn("crypto-payment-method-connect-wallet wagmi-wallet w-full rounded-xl border p-4 text-left transition-all hover:shadow-md", selectedPaymentMethod === CryptoPaymentMethodType.CONNECT_WALLET
79
+ ? "connected-wallet border-as-brand bg-as-brand/5"
80
+ : "border-as-border-secondary bg-as-surface-primary hover:border-as-secondary/80"), children: _jsxs("div", { className: "flex items-center justify-between", children: [_jsxs("div", { className: "flex items-center gap-3", children: [_jsx("div", { className: "wallet-icon flex h-10 w-10 items-center justify-center rounded-full bg-blue-100", children: _jsx(Wallet, { className: "h-5 w-5 text-blue-600" }) }), _jsxs("div", { className: "flex flex-col", children: [_jsx("span", { className: "text-as-primary font-semibold", children: connector?.name || "Connected Wallet" }), _jsx("span", { className: "text-as-primary/60 text-sm", children: shortenAddress(address || "") })] })] }), _jsxs("div", { className: "flex items-center gap-2", children: [selectedPaymentMethod === CryptoPaymentMethodType.CONNECT_WALLET && (_jsx("div", { className: "h-2 w-2 rounded-full bg-green-500" })), _jsx("button", { onClick: e => {
81
+ e.stopPropagation();
82
+ disconnect();
83
+ toast.success("Wallet disconnected");
84
+ if (selectedPaymentMethod === CryptoPaymentMethodType.CONNECT_WALLET) {
85
+ setSelectedPaymentMethod(CryptoPaymentMethodType.NONE);
86
+ }
87
+ }, className: "text-as-primary/60 hover:text-as-primary/80 rounded-lg p-1.5 transition-colors", children: _jsx(X, { className: "h-4 w-4" }) })] })] }) })), globalAddress && (_jsx("button", { onClick: () => {
88
+ setSelectedPaymentMethod(CryptoPaymentMethodType.GLOBAL_WALLET);
89
+ onSelectPaymentMethod(CryptoPaymentMethodType.GLOBAL_WALLET);
90
+ toast.success("Selected B3 Account");
91
+ }, className: cn("crypto-payment-method-global-wallet w-full rounded-xl border p-4 text-left transition-all hover:shadow-md", selectedPaymentMethod === CryptoPaymentMethodType.GLOBAL_WALLET
92
+ ? "connected-wallet border-as-brand bg-as-brand/5"
93
+ : "border-as-border-secondary bg-as-surface-primary hover:border-as-secondary/80"), children: _jsxs("div", { className: "flex items-center justify-between", children: [_jsxs("div", { className: "flex items-center gap-3", children: [_jsx(WalletImage, { fallback: _jsx("div", { className: "wallet-icon flex h-10 w-10 items-center justify-center rounded-full bg-purple-100", children: _jsx(Wallet, { className: "h-5 w-5 text-purple-600" }) }) }), _jsxs("div", { className: "flex flex-col", children: [_jsx("span", { className: "text-as-primary font-semibold", children: "Global Account" }), _jsx("span", { className: "text-as-primary/60 text-sm", children: shortenAddress(globalAddress || "") })] })] }), _jsx("div", { className: "flex items-center gap-2", children: selectedPaymentMethod === CryptoPaymentMethodType.GLOBAL_WALLET && (_jsx("div", { className: "h-2 w-2 rounded-full bg-green-500" })) })] }) }))] })] })), _jsxs("div", { className: "other-payment-methods", children: [_jsx("h3", { className: "text-as-primary/80 mb-3 text-sm font-medium", children: "Payment methods" }), _jsxs("div", { className: "space-y-3", children: [_jsxs("button", { onClick: handleConnectWallet, className: "crypto-payment-method-connect-wallet bg-as-surface-primary border-as-border-secondary hover:border-as-secondary/80 group flex w-full items-center justify-between gap-4 rounded-xl border px-4 py-3.5 transition-all duration-200 hover:shadow-md", children: [_jsxs("div", { className: "flex items-center gap-3", children: [_jsx("div", { className: "wallet-icon flex h-8 w-8 items-center justify-center rounded-full bg-blue-100", children: _jsx(Wallet, { className: "h-4 w-4 text-blue-600" }) }), _jsx("div", { className: "flex flex-col items-start text-left", children: _jsx("h4", { className: "text-as-primary font-semibold", children: "Connect wallet" }) })] }), _jsx(ChevronRightCircle, { className: "text-as-primary/40 group-hover:text-as-primary/60 h-5 w-5 transition-colors" })] }), _jsxs("button", { onClick: () => {
94
+ setSelectedPaymentMethod(CryptoPaymentMethodType.TRANSFER_CRYPTO);
95
+ onSelectPaymentMethod(CryptoPaymentMethodType.TRANSFER_CRYPTO);
96
+ }, disabled: isCreatingOrder, className: "crypto-payment-method-transfer bg-as-surface-primary border-as-border-secondary hover:border-as-secondary/80 group flex w-full items-center justify-between gap-4 rounded-xl border px-4 py-3.5 transition-all duration-200 hover:shadow-md", children: [_jsxs("div", { className: "flex items-center gap-3", children: [_jsx("div", { className: "wallet-icon flex h-8 w-8 items-center justify-center rounded-full bg-orange-100", children: _jsx(ZapIcon, { className: "h-4 w-4" }) }), _jsx("div", { className: "flex flex-col items-start text-left", children: _jsx("h4", { className: "text-as-primary font-semibold", children: "Transfer crypto" }) })] }), _jsx(ChevronRightCircle, { className: "text-as-primary/40 group-hover:text-as-primary/60 h-5 w-5 transition-colors" })] })] })] })] })] }) }));
214
97
  }
@@ -162,7 +162,7 @@ export function SignInWithB3Flow({ strategies, onLoginSuccess, onSessionKeySucce
162
162
  isOpen,
163
163
  source,
164
164
  });
165
- if (isConnected && isAuthenticated) {
165
+ if (isConnected && isAuthenticated && user) {
166
166
  // Mark that login just completed BEFORE opening manage account or closing modal
167
167
  // This allows Turnkey modal to show (if enableTurnkey is true)
168
168
  if (closeAfterLogin) {
@@ -125,14 +125,40 @@ export function useAuthentication(partnerId) {
125
125
  return userAuth;
126
126
  }
127
127
  }, [activeWallet, partnerId, authenticate, setIsAuthenticated, setIsAuthenticating, setUser, setHasStartedConnecting]);
128
+ const logout = useCallback(async (callback) => {
129
+ if (activeWallet) {
130
+ debug("@@logout:activeWallet", activeWallet);
131
+ disconnect(activeWallet);
132
+ debug("@@logout:activeWallet", activeWallet);
133
+ }
134
+ // Log out of each wallet
135
+ wallets.forEach(wallet => {
136
+ console.log("@@logging out", wallet);
137
+ disconnect(wallet);
138
+ });
139
+ // Delete localStorage thirdweb:connected-wallet-ids
140
+ // https://npc-labs.slack.com/archives/C070E6HNG85/p1750185115273099
141
+ if (typeof localStorage !== "undefined") {
142
+ localStorage.removeItem("thirdweb:connected-wallet-ids");
143
+ localStorage.removeItem("wagmi.store");
144
+ localStorage.removeItem("lastAuthProvider");
145
+ localStorage.removeItem("b3-user");
146
+ }
147
+ app.logout();
148
+ debug("@@logout:loggedOut");
149
+ setIsAuthenticated(false);
150
+ setIsConnected(false);
151
+ setUser();
152
+ callback?.();
153
+ }, [activeWallet, disconnect, wallets, setIsAuthenticated, setUser, setIsConnected]);
128
154
  const onConnect = useCallback(async (_walleAutoConnectedWith, allConnectedWallets) => {
129
155
  debug("@@useAuthentication:onConnect", { _walleAutoConnectedWith, allConnectedWallets });
130
- const wallet = allConnectedWallets.find(wallet => wallet.id.startsWith("ecosystem."));
131
- if (!wallet) {
132
- throw new Error("No smart wallet found during auto-connect");
133
- }
134
- debug("@@useAuthentication:onConnect", { wallet });
135
156
  try {
157
+ const wallet = allConnectedWallets.find(wallet => wallet.id.startsWith("ecosystem."));
158
+ if (!wallet) {
159
+ throw new Error("No smart wallet found during auto-connect");
160
+ }
161
+ debug("@@useAuthentication:onConnect", { wallet });
136
162
  setHasStartedConnecting(true);
137
163
  setIsConnected(true);
138
164
  setIsAuthenticating(true);
@@ -146,6 +172,7 @@ export function useAuthentication(partnerId) {
146
172
  debug("@@useAuthentication:onConnect:failed", { error });
147
173
  setIsAuthenticated(false);
148
174
  setUser(undefined);
175
+ await logout();
149
176
  }
150
177
  finally {
151
178
  setIsAuthenticating(false);
@@ -156,44 +183,19 @@ export function useAuthentication(partnerId) {
156
183
  isConnected,
157
184
  });
158
185
  }, [
159
- onConnectCallback,
160
- authenticateUser,
161
186
  isAuthenticated,
162
187
  isAuthenticating,
163
188
  isConnected,
164
- setActiveWallet,
165
189
  setHasStartedConnecting,
166
- setIsAuthenticated,
167
- setIsAuthenticating,
168
190
  setIsConnected,
191
+ setIsAuthenticating,
192
+ setActiveWallet,
193
+ authenticateUser,
194
+ onConnectCallback,
195
+ setIsAuthenticated,
169
196
  setUser,
197
+ logout,
170
198
  ]);
171
- const logout = useCallback(async (callback) => {
172
- if (activeWallet) {
173
- debug("@@logout:activeWallet", activeWallet);
174
- disconnect(activeWallet);
175
- debug("@@logout:activeWallet", activeWallet);
176
- }
177
- // Log out of each wallet
178
- wallets.forEach(wallet => {
179
- console.log("@@logging out", wallet);
180
- disconnect(wallet);
181
- });
182
- // Delete localStorage thirdweb:connected-wallet-ids
183
- // https://npc-labs.slack.com/archives/C070E6HNG85/p1750185115273099
184
- if (typeof localStorage !== "undefined") {
185
- localStorage.removeItem("thirdweb:connected-wallet-ids");
186
- localStorage.removeItem("wagmi.store");
187
- localStorage.removeItem("lastAuthProvider");
188
- localStorage.removeItem("b3-user");
189
- }
190
- app.logout();
191
- debug("@@logout:loggedOut");
192
- setIsAuthenticated(false);
193
- setIsConnected(false);
194
- setUser();
195
- callback?.();
196
- }, [activeWallet, disconnect, wallets, setIsAuthenticated, setUser, setIsConnected]);
197
199
  const { isLoading: useAutoConnectLoading } = useAutoConnect({
198
200
  client,
199
201
  wallets: [wallet],
@@ -2,7 +2,7 @@ import { Users } from "@b3dotfun/b3-api";
2
2
  /**
3
3
  * NOTE: THIS IS ONLY MEANT FOR INTERNAL USE, from useOnConnect
4
4
  *
5
- * Custom hook to manage user state with react-query
5
+ * Custom hook to manage user state with Zustand
6
6
  * This allows for invalidation and refetching of user data
7
7
  */
8
8
  export declare function useUserQuery(): {
@@ -59,7 +59,7 @@ export declare function useUserQuery(): {
59
59
  };
60
60
  } | undefined;
61
61
  setUser: (newUser?: Users) => void;
62
- refetchUser: () => Promise<void>;
62
+ refetchUser: () => Promise<any>;
63
63
  clearUser: () => void;
64
64
  queryKey: string[];
65
65
  };
@@ -1,77 +1,98 @@
1
1
  import { debugB3React } from "../../../shared/utils/debug.js";
2
- import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
2
+ import { useEffect } from "react";
3
+ import { create } from "zustand";
4
+ import { persist } from "zustand/middleware";
3
5
  const debug = debugB3React("useUserQuery");
4
6
  const USER_QUERY_KEY = ["b3-user"];
5
7
  /**
6
- * Retrieves the user from localStorage
8
+ * Zustand store for managing user state
9
+ * Persists user data to localStorage
7
10
  */
8
- function getUserFromStorage() {
9
- if (typeof window === "undefined") {
10
- return null;
11
- }
12
- try {
13
- const storedUser = localStorage.getItem("b3-user");
14
- return storedUser ? JSON.parse(storedUser) : null;
15
- }
16
- catch (error) {
17
- console.warn("Failed to restore user from localStorage:", error);
18
- return null;
19
- }
20
- }
21
- /**
22
- * Saves user to localStorage
23
- */
24
- function saveUserToStorage(user) {
25
- if (typeof window === "undefined") {
26
- return;
27
- }
28
- if (user) {
29
- localStorage.setItem("b3-user", JSON.stringify(user));
30
- }
31
- else {
32
- localStorage.removeItem("b3-user");
33
- }
34
- }
11
+ const useUserStore = create()(persist(set => ({
12
+ user: null,
13
+ setUser: (newUser) => {
14
+ const userToSave = newUser ?? null;
15
+ set({ user: userToSave });
16
+ debug("User updated", userToSave);
17
+ },
18
+ clearUser: () => {
19
+ set({ user: null });
20
+ debug("User cleared");
21
+ },
22
+ }), {
23
+ name: "b3-user",
24
+ onRehydrateStorage: () => (_, error) => {
25
+ if (error) {
26
+ console.warn("Failed to rehydrate user store:", error);
27
+ }
28
+ },
29
+ }));
35
30
  /**
36
31
  * NOTE: THIS IS ONLY MEANT FOR INTERNAL USE, from useOnConnect
37
32
  *
38
- * Custom hook to manage user state with react-query
33
+ * Custom hook to manage user state with Zustand
39
34
  * This allows for invalidation and refetching of user data
40
35
  */
41
36
  export function useUserQuery() {
42
- const queryClient = useQueryClient();
43
- // Query to get user data (primarily from cache/localStorage)
44
- const { data: user } = useQuery({
45
- queryKey: USER_QUERY_KEY,
46
- queryFn: getUserFromStorage,
47
- staleTime: Infinity, // User data doesn't go stale automatically
48
- gcTime: Infinity, // Keep in cache indefinitely
49
- initialData: getUserFromStorage,
50
- });
51
- // Mutation to update user
52
- const setUserMutation = useMutation({
53
- mutationFn: async (newUser) => {
54
- const userToSave = newUser ?? null;
55
- saveUserToStorage(userToSave);
56
- return userToSave;
57
- },
58
- onSuccess: data => {
59
- queryClient.setQueryData(USER_QUERY_KEY, data);
60
- debug("User updated", data);
61
- },
62
- });
37
+ const user = useUserStore(state => state.user);
38
+ const setUserStore = useUserStore(state => state.setUser);
39
+ const clearUserStore = useUserStore(state => state.clearUser);
40
+ // Listen for storage events from other tabs/windows
41
+ useEffect(() => {
42
+ const handleStorageChange = (e) => {
43
+ if (e.key === "b3-user") {
44
+ // Sync with changes from other tabs/windows
45
+ const stored = e.newValue;
46
+ if (stored) {
47
+ try {
48
+ const parsed = JSON.parse(stored);
49
+ // Zustand persist format: { state: { user: ... }, version: ... }
50
+ const userData = parsed?.state?.user ?? parsed?.user ?? null;
51
+ useUserStore.setState({ user: userData });
52
+ }
53
+ catch (error) {
54
+ console.warn("Failed to parse user from storage event:", error);
55
+ }
56
+ }
57
+ else {
58
+ useUserStore.setState({ user: null });
59
+ }
60
+ }
61
+ };
62
+ window.addEventListener("storage", handleStorageChange);
63
+ return () => {
64
+ window.removeEventListener("storage", handleStorageChange);
65
+ };
66
+ }, []);
63
67
  // Helper function to set user (maintains backward compatibility)
64
68
  const setUser = (newUser) => {
65
- setUserMutation.mutate(newUser);
69
+ setUserStore(newUser);
66
70
  };
67
71
  // Helper function to invalidate and refetch user
68
72
  const refetchUser = async () => {
69
- await queryClient.invalidateQueries({ queryKey: USER_QUERY_KEY });
70
- return queryClient.refetchQueries({ queryKey: USER_QUERY_KEY });
73
+ // Re-read from localStorage and update store
74
+ // Zustand persist stores data as { state: { user: ... }, version: ... }
75
+ const stored = localStorage.getItem("b3-user");
76
+ if (stored) {
77
+ try {
78
+ const parsed = JSON.parse(stored);
79
+ // Zustand persist format: { state: { user: ... }, version: ... }
80
+ const userData = parsed?.state?.user ?? parsed?.user ?? null;
81
+ useUserStore.setState({ user: userData });
82
+ return userData ?? undefined;
83
+ }
84
+ catch (error) {
85
+ console.warn("Failed to refetch user from localStorage:", error);
86
+ // Fallback to current store state
87
+ return useUserStore.getState().user ?? undefined;
88
+ }
89
+ }
90
+ useUserStore.setState({ user: null });
91
+ return undefined;
71
92
  };
72
93
  // Helper function to clear user
73
94
  const clearUser = () => {
74
- setUser(undefined);
95
+ clearUserStore();
75
96
  };
76
97
  return {
77
98
  user: user ?? undefined,