@bounded-sh/client 0.0.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.
Files changed (65) hide show
  1. package/README.md +298 -0
  2. package/dist/auth/hooks/useAuth.d.ts +8 -0
  3. package/dist/auth/index.d.ts +73 -0
  4. package/dist/auth/oidc-auth.d.ts +27 -0
  5. package/dist/auth/providers/email-auth-provider.d.ts +38 -0
  6. package/dist/auth/providers/guest-auth-provider.d.ts +14 -0
  7. package/dist/auth/providers/guest-keystore.d.ts +12 -0
  8. package/dist/auth/providers/mock-auth-provider.d.ts +49 -0
  9. package/dist/auth/providers/offchain-auth-provider.d.ts +56 -0
  10. package/dist/auth/providers/phantom-wallet-provider.d.ts +117 -0
  11. package/dist/auth/providers/privy-expo-provider.d.ts +115 -0
  12. package/dist/auth/providers/privy-wallet-provider.d.ts +80 -0
  13. package/dist/auth/providers/sol/sol-utils.d.ts +2 -0
  14. package/dist/auth/providers/solana-mobile-wallet-provider.d.ts +155 -0
  15. package/dist/auth/providers/transaction-utils.d.ts +10 -0
  16. package/dist/global.d.ts +13 -0
  17. package/dist/index-BHTfW8CV.esm.js +16091 -0
  18. package/dist/index-BHTfW8CV.esm.js.map +1 -0
  19. package/dist/index-C1VOdmRN.js +16130 -0
  20. package/dist/index-C1VOdmRN.js.map +1 -0
  21. package/dist/index-CT2j1oic.esm.js +16089 -0
  22. package/dist/index-CT2j1oic.esm.js.map +1 -0
  23. package/dist/index-VGx-869x.js +23572 -0
  24. package/dist/index-VGx-869x.js.map +1 -0
  25. package/dist/index-o5Hv9pfS.esm.js +23456 -0
  26. package/dist/index-o5Hv9pfS.esm.js.map +1 -0
  27. package/dist/index-sKqrgk0t.js +16132 -0
  28. package/dist/index-sKqrgk0t.js.map +1 -0
  29. package/dist/index.browser-BJZ7fYwv.js +5081 -0
  30. package/dist/index.browser-BJZ7fYwv.js.map +1 -0
  31. package/dist/index.browser-DaNhOhkQ.esm.js +4220 -0
  32. package/dist/index.browser-DaNhOhkQ.esm.js.map +1 -0
  33. package/dist/index.browser-DhAcjdpV.esm.js +5071 -0
  34. package/dist/index.browser-DhAcjdpV.esm.js.map +1 -0
  35. package/dist/index.browser-utVKQsEC.js +4225 -0
  36. package/dist/index.browser-utVKQsEC.js.map +1 -0
  37. package/dist/index.d.ts +21 -0
  38. package/dist/index.esm.js +8 -0
  39. package/dist/index.esm.js.map +1 -0
  40. package/dist/index.js +105 -0
  41. package/dist/index.js.map +1 -0
  42. package/dist/index.native-B5IBOdv_.js +19684 -0
  43. package/dist/index.native-B5IBOdv_.js.map +1 -0
  44. package/dist/index.native-JPUkdHJj.esm.js +19565 -0
  45. package/dist/index.native-JPUkdHJj.esm.js.map +1 -0
  46. package/dist/index.native.d.ts +26 -0
  47. package/dist/index.native.esm.js +6 -0
  48. package/dist/index.native.esm.js.map +1 -0
  49. package/dist/index.native.js +98 -0
  50. package/dist/index.native.js.map +1 -0
  51. package/dist/phantom-wallet-provider-CDLyxrih.js +1466 -0
  52. package/dist/phantom-wallet-provider-CDLyxrih.js.map +1 -0
  53. package/dist/phantom-wallet-provider-DMlaSrAl.esm.js +1445 -0
  54. package/dist/phantom-wallet-provider-DMlaSrAl.esm.js.map +1 -0
  55. package/dist/platform.d.ts +81 -0
  56. package/dist/privy-wallet-provider-DiHHTDbZ.js +956 -0
  57. package/dist/privy-wallet-provider-DiHHTDbZ.js.map +1 -0
  58. package/dist/privy-wallet-provider-nR52lXzI.esm.js +933 -0
  59. package/dist/privy-wallet-provider-nR52lXzI.esm.js.map +1 -0
  60. package/dist/solana-mobile-wallet-provider-B4CeMMQd.esm.js +1460 -0
  61. package/dist/solana-mobile-wallet-provider-B4CeMMQd.esm.js.map +1 -0
  62. package/dist/solana-mobile-wallet-provider-BYMfFjZb.js +1481 -0
  63. package/dist/solana-mobile-wallet-provider-BYMfFjZb.js.map +1 -0
  64. package/dist/utils.d.ts +1 -0
  65. package/package.json +100 -0
@@ -0,0 +1,1445 @@
1
+ import { W as WebSessionManager, c as convertRemainingAccounts, b as bufferExports, a as buildSetDocumentsTransaction, d as confirmAndCheckTransaction, s as setCurrentUser, S as SOLANA_DEVNET_RPC_URL, e as SOLANA_MAINNET_RPC_URL, f as SURFNET_RPC_URL, g as detectMobile, h as detectAndroid, i as getPlatform, j as setAuthLoading, k as genAuthNonce, l as genSolanaMessage, m as createSessionWithSignature } from './index.native-JPUkdHJj.esm.js';
2
+ import { Connection, PublicKey, VersionedTransaction } from '@solana/web3.js';
3
+ import * as anchor from '@coral-xyz/anchor';
4
+ import 'axios';
5
+ import 'react';
6
+
7
+ const VALID_PROVIDERS = ['injected', 'google', 'apple', 'deeplink', 'phantom'];
8
+ // When the dApp runs inside an iframe whose parent origin is different from
9
+ // (or can't inject into) the child frame — notably Phantom's Android in-app
10
+ // browser, which injects window.phantom.solana only into the top frame —
11
+ // the Phantom deeplink path tries to navigate phantom.app/ul/browse/... from
12
+ // inside the iframe. Android App Links only hand off on top-level navigations,
13
+ // and phantom.app refuses to be framed (X-Frame-Options: DENY), so the connect
14
+ // fails. To get back to a working context we navigate the top window to the
15
+ // dApp's own URL, dropping the iframe shell. Once top-level, the wallet
16
+ // browser injects its provider and the normal injected flow succeeds.
17
+ function isInIframe() {
18
+ if (typeof window === 'undefined')
19
+ return false;
20
+ try {
21
+ return window.top !== window.self;
22
+ }
23
+ catch (_a) {
24
+ // Cross-origin access to window.top throws — if we can't read it, we're iframed.
25
+ return true;
26
+ }
27
+ }
28
+ function shouldBreakOutOfIframe(provider) {
29
+ // Only break out when the user chose the deeplink provider. The modal only
30
+ // offers deeplink on mobile when no injected Phantom is present, so this is
31
+ // exactly the iframe-without-provider case we need to escape.
32
+ return provider === 'deeplink' && isInIframe();
33
+ }
34
+ // In a cross-origin iframe (e.g. the poof.new build-page preview) on mobile,
35
+ // Mobile Wallet Adapter can't run: its localhost association handshake needs
36
+ // Chrome's Local Network Access, which is denied to cross-origin sub-frames.
37
+ // So open the app's own URL TOP-LEVEL (a new tab / Custom Tab), where MWA works
38
+ // natively; the connect happens there and the session — written to same-origin
39
+ // storage — reflects back into this iframe (awaitTopLevelConnect picks it up).
40
+ // Must be called synchronously inside a user-gesture handler so window.open
41
+ // isn't popup-blocked. Returns true if the tab was opened.
42
+ function openTopLevelForConnect() {
43
+ if (typeof window === 'undefined' || !isInIframe())
44
+ return false;
45
+ try {
46
+ const url = new URL(window.location.href);
47
+ url.searchParams.set('poofConnect', '1');
48
+ const w = window.open(url.toString(), '_blank');
49
+ return !!w;
50
+ }
51
+ catch (_a) {
52
+ return false;
53
+ }
54
+ }
55
+ // Dynamically import React and Phantom SDK - only when needed
56
+ let React;
57
+ let ReactDOM;
58
+ let phantomReactSdk;
59
+ let sdkLoaded = false;
60
+ let loadingPromise = null;
61
+ // Lazy load React and Phantom dependencies only when PhantomWalletProvider is instantiated
62
+ // Uses dynamic import() to ensure code splitting and prevent side effects
63
+ async function loadDependencies() {
64
+ if (sdkLoaded)
65
+ return;
66
+ if (typeof window === 'undefined')
67
+ return;
68
+ // Prevent multiple concurrent loads
69
+ if (loadingPromise)
70
+ return loadingPromise;
71
+ loadingPromise = (async () => {
72
+ const [reactModule, reactDomModule, phantomModule] = await Promise.all([
73
+ import('react'),
74
+ import('react-dom/client'),
75
+ import('./index-CT2j1oic.esm.js')
76
+ ]);
77
+ // Extract default export from ESM module namespace
78
+ // Dynamic import() returns { default: Module, ...exports }, not the module directly
79
+ React = reactModule.default || reactModule;
80
+ ReactDOM = reactDomModule.default || reactDomModule;
81
+ phantomReactSdk = phantomModule;
82
+ sdkLoaded = true;
83
+ })();
84
+ return loadingPromise;
85
+ }
86
+ class PhantomWalletProvider {
87
+ /** Temporarily override modal appearance for a single login() call. Cleared automatically after login settles. */
88
+ setLoginOverrides(opts) {
89
+ this.loginOverrides = opts;
90
+ }
91
+ constructor(networkUrl = null, config = {}) {
92
+ this.containerElement = null;
93
+ this.root = null;
94
+ this.phantomMethods = null;
95
+ this.resolvedProviders = ['injected'];
96
+ this.pendingLogin = null;
97
+ this.loginInProgress = false;
98
+ this.autoLoginInProgress = false;
99
+ this.initPromise = null;
100
+ this.loginOverrides = null;
101
+ /** Callback to swap to a Mobile Wallet Adapter provider when the user clicks "Connect Mobile Wallet" */
102
+ this.onSwitchToMWA = null;
103
+ this.networkUrl = networkUrl;
104
+ this.config = config;
105
+ if (typeof window === 'undefined') {
106
+ throw new Error('PhantomWalletProvider can only be instantiated in a browser environment');
107
+ }
108
+ // Singleton pattern - reuse existing instance
109
+ if (PhantomWalletProvider.instance) {
110
+ return PhantomWalletProvider.instance;
111
+ }
112
+ // Resolve providers from config (doesn't need SDK)
113
+ this.resolveProviders();
114
+ // Start async initialization (load SDK and initialize React component)
115
+ this.initPromise = this.initializeAsync();
116
+ PhantomWalletProvider.instance = this;
117
+ }
118
+ async initializeAsync() {
119
+ // Lazy load dependencies only when actually instantiating
120
+ await loadDependencies();
121
+ // Initialize React component
122
+ this.initialize();
123
+ }
124
+ /**
125
+ * Check if social login providers are configured (non-injected providers).
126
+ */
127
+ hasSocialProviders() {
128
+ return this.resolvedProviders.some(p => p !== 'injected');
129
+ }
130
+ static getInstance(networkUrl, config) {
131
+ if (!PhantomWalletProvider.instance) {
132
+ new PhantomWalletProvider(networkUrl, config);
133
+ }
134
+ return PhantomWalletProvider.instance;
135
+ }
136
+ resolveProviders() {
137
+ if (this.config.providers && this.config.providers.length > 0) {
138
+ const configProviders = this.config.providers;
139
+ this.resolvedProviders = configProviders.filter((p) => VALID_PROVIDERS.includes(p));
140
+ if (this.resolvedProviders.length === 0) {
141
+ this.resolvedProviders = ['injected'];
142
+ }
143
+ }
144
+ else if (this.config.appId) {
145
+ this.resolvedProviders = ['injected', 'google', 'apple', 'deeplink'];
146
+ }
147
+ else {
148
+ this.resolvedProviders = ['injected'];
149
+ }
150
+ }
151
+ /**
152
+ * Patch the Phantom extension's provider to gracefully handle `phantom_getFeatures`
153
+ * instead of throwing. Some SDKs probe this method to check feature support, but the
154
+ * extension doesn't implement it, causing noisy console errors.
155
+ */
156
+ patchPhantomGetFeatures() {
157
+ var _a;
158
+ try {
159
+ const provider = (_a = window.phantom) === null || _a === void 0 ? void 0 : _a.solana;
160
+ if (!(provider === null || provider === void 0 ? void 0 : provider.request) || provider.__featuresPatched)
161
+ return;
162
+ const originalRequest = provider.request.bind(provider);
163
+ provider.request = async (args) => {
164
+ if ((args === null || args === void 0 ? void 0 : args.method) === 'phantom_getFeatures') {
165
+ return { features: {} };
166
+ }
167
+ return originalRequest(args);
168
+ };
169
+ provider.__featuresPatched = true;
170
+ }
171
+ catch (_b) {
172
+ // Phantom extension not present — nothing to patch
173
+ }
174
+ }
175
+ initialize() {
176
+ if (this.containerElement)
177
+ return;
178
+ // Suppress "phantom_getFeatures isn't implemented" errors from SDKs probing
179
+ // the Phantom extension for features it doesn't support yet.
180
+ this.patchPhantomGetFeatures();
181
+ // Remove any existing Phantom providers
182
+ const existingProviders = document.querySelectorAll('[data-phantom-provider]');
183
+ existingProviders.forEach(el => el.remove());
184
+ this.containerElement = document.createElement('div');
185
+ this.containerElement.setAttribute('data-phantom-provider', 'true');
186
+ // Keep Phantom UI above host overlays while avoiding global click-capture.
187
+ this.containerElement.style.position = 'fixed';
188
+ this.containerElement.style.zIndex = '2147483647';
189
+ // Full-viewport overlay for custom modal; pointer-events: none lets
190
+ // clicks pass through to page except where the modal sets 'auto'
191
+ this.containerElement.style.inset = '0';
192
+ this.containerElement.style.pointerEvents = 'none';
193
+ document.body.appendChild(this.containerElement);
194
+ const that = this;
195
+ const { PhantomProvider: ReactPhantomProvider, usePhantom, useConnect, useDisconnect, useModal, useSolana, useDiscoveredWallets, AddressType, darkTheme, lightTheme } = phantomReactSdk;
196
+ // The SDK expects providers as an array of strings: 'injected' | 'google' | 'apple' | 'phantom' | 'deeplink'
197
+ // Ensure we have a valid non-empty array
198
+ const sdkProviders = this.resolvedProviders.length > 0 ? [...this.resolvedProviders] : ['injected'];
199
+ // Inner component that uses hooks
200
+ const PhantomHooksComponent = () => {
201
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j;
202
+ const phantom = usePhantom();
203
+ const { connect, error: connectError } = useConnect();
204
+ const { disconnect, isDisconnecting } = useDisconnect();
205
+ const modal = useModal();
206
+ const solanaHook = useSolana();
207
+ const { solana } = solanaHook;
208
+ const [showWalletModal, setShowWalletModal] = React.useState(false);
209
+ const [hoveredBtn, setHoveredBtn] = React.useState(null);
210
+ // Discover all available wallets via Wallet Standard + EIP-6963
211
+ const { wallets: discoveredWallets } = useDiscoveredWallets();
212
+ const isMobile = detectMobile();
213
+ const hasPhantomInjected = discoveredWallets.some((w) => w.id === 'phantom');
214
+ const showDeeplink = isMobile && sdkProviders.includes('deeplink') && !hasPhantomInjected;
215
+ // Treat MWA's own wallet-standard registrations as not-injected, so the MWA
216
+ // button still appears when only MWA is present (e.g. Android Chrome on Seeker).
217
+ const hasInjectedWallet = discoveredWallets.some((w) => {
218
+ var _a, _b;
219
+ const id = String((_a = w.id) !== null && _a !== void 0 ? _a : '').toLowerCase();
220
+ const name = String((_b = w.name) !== null && _b !== void 0 ? _b : '').toLowerCase();
221
+ return (id !== 'mobile-wallet-adapter' &&
222
+ id !== 'remote-mobile-wallet-adapter' &&
223
+ name !== 'mobile wallet adapter' &&
224
+ name !== 'remote mobile wallet adapter');
225
+ });
226
+ // Track previous modal state to detect closes
227
+ const prevModalOpen = React.useRef(false);
228
+ // Track when modal was closed because user selected a wallet (not dismissed)
229
+ const walletClickedRef = React.useRef(false);
230
+ // Set up effect to expose methods to the class
231
+ React.useEffect(() => {
232
+ if (phantom) {
233
+ that.phantomMethods = {
234
+ ready: !phantom.isLoading,
235
+ isConnected: phantom.isConnected,
236
+ addresses: phantom.addresses || [],
237
+ user: phantom.user,
238
+ connect: async () => {
239
+ return await connect();
240
+ },
241
+ disconnect: async () => {
242
+ await disconnect();
243
+ },
244
+ isDisconnecting,
245
+ openModal: () => modal.open(),
246
+ closeModal: () => modal.close(),
247
+ isModalOpen: modal.isOpened,
248
+ connectError,
249
+ showCustomModal: () => setShowWalletModal(true),
250
+ hideCustomModal: () => setShowWalletModal(false),
251
+ solana: solana && solanaHook.isAvailable ? {
252
+ // Wrap methods to preserve 'this' context - direct references lose binding
253
+ signMessage: (message) => solana.signMessage(message),
254
+ signTransaction: (tx) => solana.signTransaction(tx),
255
+ signAllTransactions: (txs) => solana.signAllTransactions(txs),
256
+ signAndSendTransaction: (tx) => solana.signAndSendTransaction(tx),
257
+ getPublicKey: () => solana.getPublicKey(),
258
+ isAvailable: solanaHook.isAvailable,
259
+ connected: solana.connected,
260
+ connect: (options) => solana.connect(options),
261
+ } : null,
262
+ };
263
+ }
264
+ }, [phantom, phantom === null || phantom === void 0 ? void 0 : phantom.isConnected, phantom === null || phantom === void 0 ? void 0 : phantom.addresses, phantom === null || phantom === void 0 ? void 0 : phantom.isLoading, connect, disconnect, isDisconnecting, modal, modal.isOpened, solana, solana === null || solana === void 0 ? void 0 : solana.connected, solanaHook.isAvailable, connectError]);
265
+ // Auto-login: If connected but no Tarobase session, try to create one.
266
+ // This handles social login callbacks where user returns from OAuth already connected.
267
+ React.useEffect(() => {
268
+ const autoCreateSession = async () => {
269
+ var _a;
270
+ // Only proceed when SDK is ready, connected, has addresses, and not already in a login flow
271
+ if (!(phantom === null || phantom === void 0 ? void 0 : phantom.isConnected) || (phantom === null || phantom === void 0 ? void 0 : phantom.isLoading) || that.loginInProgress || that.autoLoginInProgress || that.pendingLogin) {
272
+ return;
273
+ }
274
+ // Don't clobber a session owned by MWA on Seeker. MWA marks the
275
+ // auth method as soon as login starts (see solana-mobile-wallet-provider),
276
+ // and clears it on logout, so this guard is correct in both
277
+ // steady-state and post-logout cases.
278
+ try {
279
+ if (getPlatform().storage.getItem('tarobase_last_auth_method') === 'mobile-wallet-adapter') {
280
+ return;
281
+ }
282
+ }
283
+ catch (_b) { }
284
+ // Need solana to be available AND connected for signing
285
+ if (!solana || !solanaHook.isAvailable || !solana.connected) {
286
+ return;
287
+ }
288
+ // Find Solana address
289
+ const solAddress = (_a = phantom.addresses) === null || _a === void 0 ? void 0 : _a.find((addr) => addr.addressType === AddressType.solana);
290
+ if (!solAddress) {
291
+ return;
292
+ }
293
+ const publicKey = solAddress.address;
294
+ // Check if we already have a valid session for this address
295
+ const existingSession = await WebSessionManager.getSession();
296
+ if (existingSession && existingSession.address === publicKey) {
297
+ // Already have a valid session, just set user
298
+ setCurrentUser({ provider: that, address: publicKey });
299
+ return;
300
+ }
301
+ // No valid session - try to create one automatically
302
+ that.autoLoginInProgress = true;
303
+ setAuthLoading(true);
304
+ try {
305
+ const nonce = await genAuthNonce();
306
+ const messageText = await genSolanaMessage(publicKey, nonce);
307
+ // signMessage returns { signature: Uint8Array, publicKey: string }
308
+ const signResult = await solana.signMessage(messageText);
309
+ // Convert Uint8Array signature to base64 string
310
+ const signatureBytes = signResult.signature;
311
+ const signature = bufferExports.Buffer.from(signatureBytes).toString('base64');
312
+ const createSessionResult = await createSessionWithSignature(publicKey, messageText, signature);
313
+ // Pre-write guard: MWA may have started a login while we were
314
+ // in flight. If MWA owns the auth method now, abort before we
315
+ // overwrite its session (or its in-flight session).
316
+ try {
317
+ if (getPlatform().storage.getItem('tarobase_last_auth_method') === 'mobile-wallet-adapter') {
318
+ return;
319
+ }
320
+ }
321
+ catch (_c) { }
322
+ await WebSessionManager.storeSession(publicKey, createSessionResult.accessToken, createSessionResult.idToken, createSessionResult.refreshToken);
323
+ // Mark auth method so clearIncompatibleSession() doesn't wipe this session
324
+ try {
325
+ getPlatform().storage.setItem('tarobase_last_auth_method', 'phantom');
326
+ }
327
+ catch (_d) { }
328
+ setCurrentUser({ provider: that, address: publicKey });
329
+ }
330
+ catch (error) {
331
+ // User rejected signing or other error - disconnect fully
332
+ try {
333
+ await disconnect();
334
+ }
335
+ catch (e) {
336
+ // Ignore disconnect errors
337
+ }
338
+ }
339
+ finally {
340
+ that.autoLoginInProgress = false;
341
+ setAuthLoading(false);
342
+ }
343
+ };
344
+ autoCreateSession();
345
+ }, [phantom === null || phantom === void 0 ? void 0 : phantom.isConnected, phantom === null || phantom === void 0 ? void 0 : phantom.isLoading, phantom === null || phantom === void 0 ? void 0 : phantom.addresses, solana, solana === null || solana === void 0 ? void 0 : solana.connected, solanaHook.isAvailable, disconnect]);
346
+ // Suppress SDK modal if it opens during custom modal login flow
347
+ React.useEffect(() => {
348
+ if (modal.isOpened && that.loginInProgress) {
349
+ modal.close();
350
+ }
351
+ }, [modal.isOpened]);
352
+ // Handle modal close without connection
353
+ React.useEffect(() => {
354
+ // Detect when modal was open and is now closed
355
+ if (prevModalOpen.current && !showWalletModal && !modal.isOpened) {
356
+ if (walletClickedRef.current) {
357
+ // Modal closed because user selected a wallet — don't reject
358
+ walletClickedRef.current = false;
359
+ }
360
+ else if (that.loginInProgress && that.pendingLogin && !(phantom === null || phantom === void 0 ? void 0 : phantom.isConnected)) {
361
+ // User dismissed modal without connecting
362
+ that.pendingLogin.reject(new Error('User cancelled login'));
363
+ that.pendingLogin = null;
364
+ that.loginInProgress = false;
365
+ }
366
+ }
367
+ prevModalOpen.current = showWalletModal || modal.isOpened;
368
+ }, [showWalletModal, modal.isOpened, phantom === null || phantom === void 0 ? void 0 : phantom.isConnected]);
369
+ // Handle connection errors
370
+ React.useEffect(() => {
371
+ if (connectError && that.pendingLogin) {
372
+ that.pendingLogin.reject(connectError);
373
+ that.pendingLogin = null;
374
+ that.loginInProgress = false;
375
+ }
376
+ }, [connectError]);
377
+ // Handle connection success
378
+ React.useEffect(() => {
379
+ const handleConnectionSuccess = async () => {
380
+ var _a;
381
+ // All conditions must be met for login to proceed
382
+ if (!(phantom === null || phantom === void 0 ? void 0 : phantom.isConnected) || !((_a = phantom === null || phantom === void 0 ? void 0 : phantom.addresses) === null || _a === void 0 ? void 0 : _a.length) || !that.pendingLogin || !that.loginInProgress) {
383
+ return;
384
+ }
385
+ // Solana must be available AND connected for signing
386
+ // If not ready yet, just return - this effect will re-run when solana.connected changes
387
+ if (!solana || !solanaHook.isAvailable || !solana.connected) {
388
+ return;
389
+ }
390
+ try {
391
+ // Immediately set loginInProgress to false to prevent double execution
392
+ // if the effect runs again before async operations complete
393
+ that.loginInProgress = false;
394
+ // Find Solana address
395
+ const solAddress = phantom.addresses.find((addr) => addr.addressType === AddressType.solana);
396
+ if (!solAddress) {
397
+ that.pendingLogin.reject(new Error('No Solana address returned'));
398
+ that.pendingLogin = null;
399
+ return;
400
+ }
401
+ const publicKey = solAddress.address;
402
+ // Check if we already have a valid session
403
+ const existingSession = await WebSessionManager.getSession();
404
+ if (existingSession && existingSession.address === publicKey) {
405
+ const user = { provider: that, address: publicKey };
406
+ setCurrentUser(user);
407
+ that.pendingLogin.resolve(user);
408
+ that.pendingLogin = null;
409
+ return;
410
+ }
411
+ // Create new session with signature
412
+ const nonce = await genAuthNonce();
413
+ const messageText = await genSolanaMessage(publicKey, nonce);
414
+ // signMessage returns { signature: Uint8Array, publicKey: string }
415
+ const signResult = await solana.signMessage(messageText);
416
+ // Convert Uint8Array signature to base64 string
417
+ const signatureBytes = signResult.signature;
418
+ const signature = bufferExports.Buffer.from(signatureBytes).toString('base64');
419
+ const createSessionResult = await createSessionWithSignature(publicKey, messageText, signature);
420
+ await WebSessionManager.storeSession(publicKey, createSessionResult.accessToken, createSessionResult.idToken, createSessionResult.refreshToken);
421
+ // Mark auth method so clearIncompatibleSession() doesn't wipe this session
422
+ try {
423
+ getPlatform().storage.setItem('tarobase_last_auth_method', 'phantom');
424
+ }
425
+ catch (_b) { }
426
+ const user = { provider: that, address: publicKey };
427
+ setCurrentUser(user);
428
+ that.pendingLogin.resolve(user);
429
+ that.pendingLogin = null;
430
+ }
431
+ catch (error) {
432
+ // Disconnect Phantom since login failed - don't leave in half-connected state
433
+ try {
434
+ await disconnect();
435
+ }
436
+ catch (e) {
437
+ // Ignore disconnect errors
438
+ }
439
+ if (that.pendingLogin) {
440
+ that.pendingLogin.reject(error);
441
+ that.pendingLogin = null;
442
+ that.loginInProgress = false;
443
+ }
444
+ }
445
+ };
446
+ handleConnectionSuccess();
447
+ }, [phantom === null || phantom === void 0 ? void 0 : phantom.isConnected, phantom === null || phantom === void 0 ? void 0 : phantom.addresses, solana, solana === null || solana === void 0 ? void 0 : solana.connected, solanaHook.isAvailable]);
448
+ // --- Custom wallet modal handlers ---
449
+ const handleWalletClick = async (options) => {
450
+ walletClickedRef.current = true;
451
+ setShowWalletModal(false);
452
+ // Cross-origin preview iframe + deeplink: the old approach navigated
453
+ // the top frame to this URL, but in a TWA that lands out-of-scope and
454
+ // shows a chrome-error ("bad page"). Instead, open the app TOP-LEVEL
455
+ // in a new tab where the wallet connect works natively; the session
456
+ // reflects back into this iframe (see openTopLevelForConnect /
457
+ // awaitTopLevelConnect).
458
+ if (shouldBreakOutOfIframe(options === null || options === void 0 ? void 0 : options.provider)) {
459
+ if (openTopLevelForConnect()) {
460
+ that.awaitTopLevelConnect();
461
+ return;
462
+ }
463
+ // Popup blocked — fall through to the original deeplink path
464
+ // (better a broken-ish button than a silently-dead one).
465
+ }
466
+ try {
467
+ if (options === null || options === void 0 ? void 0 : options.walletId) {
468
+ await connect({ provider: 'injected', walletId: options.walletId });
469
+ }
470
+ else if (options === null || options === void 0 ? void 0 : options.provider) {
471
+ await connect({ provider: options.provider });
472
+ }
473
+ else {
474
+ await connect();
475
+ }
476
+ }
477
+ catch (err) {
478
+ // connectError effect handles this
479
+ }
480
+ };
481
+ const handleMobileWalletClick = async () => {
482
+ that.loginInProgress = false;
483
+ walletClickedRef.current = true;
484
+ setShowWalletModal(false);
485
+ // Cross-origin preview iframe (e.g. poof.new build page) on mobile:
486
+ // MWA can't run here (Chrome denies Local Network Access to sub-frames,
487
+ // and its localhost handshake fails). Open the app top-level for the
488
+ // connect; the session reflects back into this iframe.
489
+ if (isInIframe() && openTopLevelForConnect()) {
490
+ that.awaitTopLevelConnect();
491
+ return;
492
+ }
493
+ // LNA permission is handled by @solana-mobile/wallet-standard-mobile
494
+ // >=0.5.0's checkLocalNetworkAccessPermission (three-stage UX, fired
495
+ // before the localhost reflector opens). No homemade pre-warm needed.
496
+ if (that.onSwitchToMWA) {
497
+ try {
498
+ const mwaProvider = await that.onSwitchToMWA();
499
+ const user = await mwaProvider.login();
500
+ if (that.pendingLogin && user) {
501
+ that.pendingLogin.resolve(user);
502
+ that.pendingLogin = null;
503
+ }
504
+ else if (that.pendingLogin) {
505
+ that.pendingLogin.reject(new Error('User cancelled login'));
506
+ that.pendingLogin = null;
507
+ }
508
+ }
509
+ catch (error) {
510
+ if (that.pendingLogin) {
511
+ that.pendingLogin.reject(error);
512
+ that.pendingLogin = null;
513
+ }
514
+ }
515
+ }
516
+ };
517
+ const handleCloseModal = () => {
518
+ setShowWalletModal(false);
519
+ if (that.loginInProgress && that.pendingLogin && !(phantom === null || phantom === void 0 ? void 0 : phantom.isConnected)) {
520
+ that.pendingLogin.reject(new Error('User cancelled login'));
521
+ that.pendingLogin = null;
522
+ that.loginInProgress = false;
523
+ }
524
+ };
525
+ // --- Custom wallet modal ---
526
+ if (!showWalletModal) {
527
+ return null;
528
+ }
529
+ const effectiveTheme = (_c = (_b = (_a = that.loginOverrides) === null || _a === void 0 ? void 0 : _a.theme) !== null && _b !== void 0 ? _b : that.config.theme) !== null && _c !== void 0 ? _c : 'dark';
530
+ const isLight = effectiveTheme === 'light';
531
+ const bgColor = isLight ? '#FFFFFF' : '#111113';
532
+ const cardBorder = isLight ? '1px solid rgba(0,0,0,0.08)' : '1px solid rgba(255,255,255,0.07)';
533
+ const textColor = isLight ? '#0f0f0f' : '#f5f5f5';
534
+ const subTextColor = isLight ? 'rgba(0,0,0,0.45)' : 'rgba(255,255,255,0.4)';
535
+ const btnBg = isLight ? 'rgba(0,0,0,0.04)' : 'rgba(255,255,255,0.05)';
536
+ const btnHoverBg = isLight ? 'rgba(0,0,0,0.08)' : 'rgba(255,255,255,0.09)';
537
+ const btnBorder = isLight ? '1px solid rgba(0,0,0,0.10)' : '1px solid rgba(255,255,255,0.09)';
538
+ const fontFamily = '"SF Pro Text",-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif';
539
+ const buttonStyle = (id) => ({
540
+ display: 'flex',
541
+ alignItems: 'center',
542
+ justifyContent: 'center',
543
+ gap: '10px',
544
+ width: '100%',
545
+ height: '52px',
546
+ padding: '0 20px',
547
+ border: btnBorder,
548
+ borderRadius: '12px',
549
+ backgroundColor: hoveredBtn === id ? btnHoverBg : btnBg,
550
+ color: textColor,
551
+ fontFamily,
552
+ fontSize: '14px',
553
+ fontWeight: '500',
554
+ lineHeight: '1',
555
+ letterSpacing: '0',
556
+ cursor: 'pointer',
557
+ transition: 'background-color 0.15s, border-color 0.15s',
558
+ boxSizing: 'border-box',
559
+ });
560
+ const walletButtons = [];
561
+ // Google OAuth button — shown when 'google' is in resolved providers
562
+ if (sdkProviders.includes('google')) {
563
+ walletButtons.push(React.createElement('button', {
564
+ key: 'google-oauth',
565
+ style: buttonStyle('google-oauth'),
566
+ onClick: () => handleWalletClick({ provider: 'google' }),
567
+ onMouseEnter: () => setHoveredBtn('google-oauth'),
568
+ onMouseLeave: () => setHoveredBtn(null),
569
+ }, React.createElement('svg', {
570
+ width: '18', height: '18', viewBox: '0 0 24 24',
571
+ style: { flexShrink: '0' },
572
+ }, React.createElement('path', {
573
+ d: 'M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92a5.06 5.06 0 0 1-2.2 3.32v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.1z',
574
+ fill: '#4285F4',
575
+ }), React.createElement('path', {
576
+ d: 'M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z',
577
+ fill: '#34A853',
578
+ }), React.createElement('path', {
579
+ d: 'M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18A11.96 11.96 0 0 0 1 12c0 1.94.46 3.77 1.18 5.41l3.66-2.84z',
580
+ fill: '#FBBC05',
581
+ }), React.createElement('path', {
582
+ d: 'M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z',
583
+ fill: '#EA4335',
584
+ })), 'Continue with Google'));
585
+ }
586
+ // Apple OAuth button — shown when 'apple' is in resolved providers
587
+ if (sdkProviders.includes('apple')) {
588
+ walletButtons.push(React.createElement('button', {
589
+ key: 'apple-oauth',
590
+ style: buttonStyle('apple-oauth'),
591
+ onClick: () => handleWalletClick({ provider: 'apple' }),
592
+ onMouseEnter: () => setHoveredBtn('apple-oauth'),
593
+ onMouseLeave: () => setHoveredBtn(null),
594
+ }, React.createElement('svg', {
595
+ width: '18', height: '18', viewBox: '0 0 24 24',
596
+ fill: textColor,
597
+ style: { flexShrink: '0' },
598
+ }, React.createElement('path', {
599
+ d: 'M17.05 20.28c-.98.95-2.05.88-3.08.4-1.09-.5-2.08-.48-3.24 0-1.44.62-2.2.44-3.06-.4C2.79 15.25 3.51 7.59 9.05 7.31c1.35.07 2.29.74 3.08.8 1.18-.24 2.31-.93 3.57-.84 1.51.12 2.65.72 3.4 1.8-3.12 1.87-2.38 5.98.48 7.13-.57 1.5-1.31 2.99-2.54 4.09zM12.03 7.25c-.15-2.23 1.66-4.07 3.74-4.25.29 2.58-2.34 4.5-3.74 4.25z',
600
+ })), 'Continue with Apple'));
601
+ }
602
+ // Fallback icon for Phantom — uses the official SVG path from @phantom/wallet-sdk-ui
603
+ // (SDK intentionally leaves wallet.icon empty for Phantom, expecting its own UI to render it)
604
+ const PHANTOM_ICON = 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjgiIGhlaWdodD0iMjgiIHZpZXdCb3g9IjAgMCAyOCAyOCIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48cmVjdCB3aWR0aD0iMjgiIGhlaWdodD0iMjgiIHJ4PSI2IiBmaWxsPSIjQUI5RkYyIi8+PGcgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoNCw0KSI+PHBhdGggZD0iTTIuMzY2NTUgMTguMzI3MUM0LjkxODcxIDE4LjMyNzEgNi44MzY3IDE2LjEwNzYgNy45ODEzMSAxNC4zNTM3QzcuODQyMSAxNC43NDE3IDcuNzY0NzYgMTUuMTI5OCA3Ljc2NDc2IDE1LjUwMjNDNy43NjQ3NiAxNi41MjY3IDguMzUyNTMgMTcuMjU2MiA5LjUxMjYgMTcuMjU2MkMxMS4xMDU4IDE3LjI1NjIgMTIuODA3MiAxNS44NTkzIDEzLjY4ODkgMTQuMzUzN0MxMy42MjcgMTQuNTcxIDEzLjU5NjEgMTQuNzcyOCAxMy41OTYxIDE0Ljk1OUMxMy41OTYxIDE1LjY3MyAxMy45OTgyIDE2LjEyMzEgMTQuODE4IDE2LjEyMzFDMTcuNDAxMSAxNi4xMjMxIDE5Ljk5OTcgMTEuNTQ0NCAxOS45OTk3IDcuNTM5ODdDMTkuOTk5NyA0LjQyMDExIDE4LjQyMiAxLjY3Mjg1IDE0LjQ2MjIgMS42NzI4NUM3LjUwMTgxIDEuNjcyODUgMCAxMC4xNzg1IDAgMTUuNjczQzAgMTcuODMwNSAxLjE2MDA3IDE4LjMyNzEgMi4zNjY1NSAxOC4zMjcxWk0xMi4wNjQ4IDcuMTk4NDFDMTIuMDY0OCA2LjQyMjM1IDEyLjQ5NzkgNS44NzkxIDEzLjEzMiA1Ljg3OTFDMTMuNzUwNyA1Ljg3OTEgMTQuMTgzOCA2LjQyMjM1IDE0LjE4MzggNy4xOTg0MUMxNC4xODM4IDcuOTc0NDcgMTMuNzUwNyA4LjUzMzIzIDEzLjEzMiA4LjUzMzIzQzEyLjQ5NzkgOC41MzMyMyAxMi4wNjQ4IDcuOTc0NDcgMTIuMDY0OCA3LjE5ODQxWk0xNS4zNzQ4IDcuMTk4NDFDMTUuMzc0OCA2LjQyMjM1IDE1LjgwNzkgNS44NzkxIDE2LjQ0MjEgNS44NzkxQzE3LjA2MDggNS44NzkxIDE3LjQ5MzkgNi40MjIzNSAxNy40OTM5IDcuMTk4NDFDMTcuNDkzOSA3Ljk3NDQ3IDE3LjA2MDggOC41MzMyMyAxNi40NDIxIDguNTMzMjNDMTUuODA3OSA4LjUzMzIzIDE1LjM3NDggNy45NzQ0NyAxNS4zNzQ4IDcuMTk4NDFaIiBmaWxsPSJ3aGl0ZSIvPjwvZz48L3N2Zz4=';
605
+ // Show all discovered injected wallets (Phantom, Solflare, Jupiter, etc.)
606
+ if (sdkProviders.includes('injected')) {
607
+ for (const wallet of discoveredWallets) {
608
+ const walletKey = `wallet-${wallet.id}`;
609
+ const iconSrc = wallet.icon || (wallet.id === 'phantom' ? PHANTOM_ICON : null);
610
+ walletButtons.push(React.createElement('button', {
611
+ key: walletKey,
612
+ style: buttonStyle(walletKey),
613
+ onClick: () => handleWalletClick({ walletId: wallet.id }),
614
+ onMouseEnter: () => setHoveredBtn(walletKey),
615
+ onMouseLeave: () => setHoveredBtn(null),
616
+ }, iconSrc
617
+ ? React.createElement('img', {
618
+ src: iconSrc,
619
+ alt: wallet.name,
620
+ style: { width: '28px', height: '28px', borderRadius: '6px' },
621
+ })
622
+ : null, wallet.name));
623
+ }
624
+ }
625
+ if (showDeeplink) {
626
+ walletButtons.push(React.createElement('button', {
627
+ key: 'phantom-deeplink',
628
+ style: buttonStyle('phantom-deeplink'),
629
+ onClick: () => handleWalletClick({ provider: 'deeplink' }),
630
+ onMouseEnter: () => setHoveredBtn('phantom-deeplink'),
631
+ onMouseLeave: () => setHoveredBtn(null),
632
+ }, React.createElement('img', {
633
+ src: PHANTOM_ICON,
634
+ alt: 'Phantom',
635
+ style: { width: '28px', height: '28px', borderRadius: '6px' },
636
+ }), 'Open Phantom app'));
637
+ }
638
+ // Mobile Wallet Adapter button — shown on Android when MWA callback is available
639
+ // and no injected wallet is present (hides button inside Phantom/Solflare/etc. in-app browsers).
640
+ const isAndroid = detectAndroid();
641
+ if (isAndroid && that.onSwitchToMWA && !hasInjectedWallet) {
642
+ walletButtons.push(React.createElement('button', {
643
+ key: 'mobile-wallet',
644
+ style: buttonStyle('mobile-wallet'),
645
+ onClick: handleMobileWalletClick,
646
+ onMouseEnter: () => setHoveredBtn('mobile-wallet'),
647
+ onMouseLeave: () => setHoveredBtn(null),
648
+ }, React.createElement('svg', {
649
+ width: '18', height: '18', viewBox: '0 0 24 24', fill: 'none',
650
+ style: { flexShrink: '0', opacity: '0.85' },
651
+ },
652
+ // Phone outline
653
+ React.createElement('rect', {
654
+ x: '5', y: '2', width: '14', height: '20', rx: '2',
655
+ stroke: textColor, strokeWidth: '2', fill: 'none',
656
+ }),
657
+ // Screen line
658
+ React.createElement('line', {
659
+ x1: '5', y1: '6', x2: '19', y2: '6',
660
+ stroke: textColor, strokeWidth: '1.5',
661
+ }),
662
+ // Wallet/shield checkmark
663
+ React.createElement('path', {
664
+ d: 'M9.5 12.5l2 2 3.5-3.5',
665
+ stroke: textColor, strokeWidth: '2', strokeLinecap: 'round', strokeLinejoin: 'round', fill: 'none',
666
+ })), 'Connect Mobile Wallet'));
667
+ }
668
+ const mainButtons = walletButtons;
669
+ // Render custom modal
670
+ return React.createElement('div', {
671
+ // Overlay
672
+ style: {
673
+ position: 'fixed',
674
+ top: '0',
675
+ left: '0',
676
+ right: '0',
677
+ bottom: '0',
678
+ backgroundColor: isLight ? 'rgba(0,0,0,0.35)' : 'rgba(0,0,0,0.65)',
679
+ display: 'flex',
680
+ alignItems: 'center',
681
+ justifyContent: 'center',
682
+ padding: '16px',
683
+ boxSizing: 'border-box',
684
+ overflowY: 'auto',
685
+ zIndex: 2147483647,
686
+ pointerEvents: 'auto',
687
+ backdropFilter: 'blur(4px)',
688
+ WebkitBackdropFilter: 'blur(4px)',
689
+ },
690
+ onClick: (e) => {
691
+ if (e.target === e.currentTarget)
692
+ handleCloseModal();
693
+ },
694
+ onMouseDown: (e) => {
695
+ e.stopPropagation();
696
+ },
697
+ onPointerDown: (e) => {
698
+ e.stopPropagation();
699
+ },
700
+ },
701
+ // Card
702
+ React.createElement('div', {
703
+ style: {
704
+ backgroundColor: bgColor,
705
+ border: cardBorder,
706
+ borderRadius: '20px',
707
+ width: '100%',
708
+ maxWidth: '380px',
709
+ maxHeight: '100%',
710
+ overflowY: 'auto',
711
+ padding: '28px 24px 24px',
712
+ position: 'relative',
713
+ boxShadow: isLight
714
+ ? '0 8px 40px rgba(0,0,0,0.12), 0 2px 8px rgba(0,0,0,0.06)'
715
+ : '0 8px 40px rgba(0,0,0,0.6), 0 2px 8px rgba(0,0,0,0.3)',
716
+ pointerEvents: 'auto',
717
+ boxSizing: 'border-box',
718
+ },
719
+ onMouseDown: (e) => {
720
+ e.stopPropagation();
721
+ },
722
+ onPointerDown: (e) => {
723
+ e.stopPropagation();
724
+ },
725
+ },
726
+ // Close button
727
+ React.createElement('button', {
728
+ onClick: handleCloseModal,
729
+ style: {
730
+ position: 'absolute',
731
+ top: '14px',
732
+ right: '14px',
733
+ background: isLight ? 'rgba(0,0,0,0.05)' : 'rgba(255,255,255,0.07)',
734
+ border: isLight ? '1px solid rgba(0,0,0,0.08)' : '1px solid rgba(255,255,255,0.08)',
735
+ borderRadius: '50%',
736
+ width: '28px',
737
+ height: '28px',
738
+ cursor: 'pointer',
739
+ display: 'flex',
740
+ alignItems: 'center',
741
+ justifyContent: 'center',
742
+ padding: '0',
743
+ flexShrink: '0',
744
+ },
745
+ }, React.createElement('svg', {
746
+ width: '12', height: '12', viewBox: '0 0 12 12', fill: 'none',
747
+ }, React.createElement('path', {
748
+ d: 'M11 1L1 11M1 1l10 10',
749
+ stroke: subTextColor, strokeWidth: '1.75', strokeLinecap: 'round',
750
+ }))),
751
+ // App icon (if provided)
752
+ that.config.appIcon ? React.createElement('div', {
753
+ style: { display: 'flex', justifyContent: 'center', marginBottom: '16px' },
754
+ }, React.createElement('img', {
755
+ src: that.config.appIcon,
756
+ alt: that.config.appName || 'App',
757
+ style: { width: '44px', height: '44px', borderRadius: '10px' },
758
+ })) : null,
759
+ // Title
760
+ React.createElement('div', {
761
+ style: {
762
+ color: textColor,
763
+ fontFamily,
764
+ fontSize: '17px',
765
+ fontWeight: '600',
766
+ textAlign: 'center',
767
+ marginBottom: '6px',
768
+ letterSpacing: '-0.2px',
769
+ },
770
+ }, (_f = (_e = (_d = that.loginOverrides) === null || _d === void 0 ? void 0 : _d.modalTitle) !== null && _e !== void 0 ? _e : that.config.modalTitle) !== null && _f !== void 0 ? _f : (that.config.appName ? `Log in to ${that.config.appName}` : 'Log in to your account')),
771
+ // Subtitle
772
+ React.createElement('div', {
773
+ style: {
774
+ color: subTextColor,
775
+ fontFamily,
776
+ fontSize: '13px',
777
+ fontWeight: '400',
778
+ textAlign: 'center',
779
+ marginBottom: '24px',
780
+ lineHeight: '1.4',
781
+ },
782
+ }, (_j = (_h = (_g = that.loginOverrides) === null || _g === void 0 ? void 0 : _g.modalSubtitle) !== null && _h !== void 0 ? _h : that.config.modalSubtitle) !== null && _j !== void 0 ? _j : 'Choose how you\'d like to continue'),
783
+ // Wallet / social login buttons
784
+ React.createElement('div', {
785
+ style: {
786
+ display: 'flex',
787
+ flexDirection: 'column',
788
+ gap: '8px',
789
+ },
790
+ }, ...mainButtons)));
791
+ };
792
+ // Wrapper component with PhantomProvider
793
+ const PhantomProviderWrapper = () => {
794
+ // Build SDK config
795
+ const sdkConfig = React.useMemo(() => {
796
+ var _a;
797
+ const config = {
798
+ providers: sdkProviders,
799
+ addressTypes: [AddressType.solana],
800
+ autoConnect: (_a = that.config.autoConnect) !== null && _a !== void 0 ? _a : true,
801
+ };
802
+ if (that.config.appId) {
803
+ config.appId = that.config.appId;
804
+ }
805
+ return config;
806
+ }, []);
807
+ const theme = that.config.theme === 'light' ? lightTheme : darkTheme;
808
+ return React.createElement(ReactPhantomProvider, {
809
+ config: sdkConfig,
810
+ theme: theme,
811
+ appName: that.config.appName || 'App',
812
+ appIcon: that.config.appIcon,
813
+ }, React.createElement(PhantomHooksComponent));
814
+ };
815
+ this.root = ReactDOM.createRoot(this.containerElement);
816
+ this.root.render(React.createElement(PhantomProviderWrapper));
817
+ }
818
+ async ensureReady() {
819
+ // Wait for async initialization to complete first
820
+ if (this.initPromise) {
821
+ await this.initPromise;
822
+ }
823
+ // Wait for SDK to be ready
824
+ await new Promise((resolve) => {
825
+ const check = () => {
826
+ var _a;
827
+ if ((_a = this.phantomMethods) === null || _a === void 0 ? void 0 : _a.ready) {
828
+ resolve();
829
+ }
830
+ else {
831
+ setTimeout(check, 100);
832
+ }
833
+ };
834
+ check();
835
+ });
836
+ }
837
+ async ensureSolanaReady() {
838
+ var _a;
839
+ await this.ensureReady();
840
+ // If connected at the Phantom level, ensure solana methods are ready
841
+ if ((_a = this.phantomMethods) === null || _a === void 0 ? void 0 : _a.isConnected) {
842
+ const timeoutMs = 10000; // 10 second timeout
843
+ const startTime = Date.now();
844
+ // First, wait for solana to be available
845
+ await new Promise((resolve, reject) => {
846
+ const check = () => {
847
+ var _a, _b;
848
+ if ((_b = (_a = this.phantomMethods) === null || _a === void 0 ? void 0 : _a.solana) === null || _b === void 0 ? void 0 : _b.isAvailable) {
849
+ resolve();
850
+ }
851
+ else if (Date.now() - startTime > timeoutMs) {
852
+ reject(new Error('Timeout waiting for Solana provider to be available'));
853
+ }
854
+ else {
855
+ setTimeout(check, 100);
856
+ }
857
+ };
858
+ check();
859
+ });
860
+ // Now check if the solana provider is connected, if not try to reconnect
861
+ // Note: We check our wrapper's `connected` which may be stale, but this is just
862
+ // an optimization to skip reconnect if we know we're already connected.
863
+ // The actual signing methods use the SDK's bound methods which check live state.
864
+ if (!this.phantomMethods.solana.connected) {
865
+ console.log('Solana provider not connected, attempting to reconnect...');
866
+ try {
867
+ // onlyIfTrusted: true means it will reconnect silently if previously approved
868
+ // If not trusted, it will throw and we'll catch it below
869
+ await this.phantomMethods.solana.connect({ onlyIfTrusted: true });
870
+ console.log('Solana provider reconnected successfully');
871
+ }
872
+ catch (error) {
873
+ // If onlyIfTrusted fails, the user may need to re-approve via modal
874
+ console.error('Failed to reconnect solana provider (silent reconnect failed):', error === null || error === void 0 ? void 0 : error.message);
875
+ throw new Error('Failed to reconnect Solana provider. Please try logging in again.');
876
+ }
877
+ }
878
+ // Note: We don't do a final connected check here because our wrapper's `connected`
879
+ // is a snapshot that won't update until React re-renders. If connect() succeeded,
880
+ // the SDK is connected and signing will work.
881
+ }
882
+ }
883
+ /**
884
+ * Get the list of available (configured) providers for this wallet.
885
+ */
886
+ getAvailableProviders() {
887
+ return [...this.resolvedProviders];
888
+ }
889
+ /**
890
+ * Login using the Phantom connect modal. A custom modal is rendered with the
891
+ * discovered wallets and configured social providers instead of the SDK's
892
+ * built-in modal.
893
+ */
894
+ async login() {
895
+ var _a, _b;
896
+ await this.ensureReady();
897
+ // Check if already connected with valid session
898
+ if (((_a = this.phantomMethods) === null || _a === void 0 ? void 0 : _a.isConnected) && ((_b = this.phantomMethods.addresses) === null || _b === void 0 ? void 0 : _b.length) > 0) {
899
+ const solAddress = this.phantomMethods.addresses.find((addr) => addr.addressType === phantomReactSdk.AddressType.solana);
900
+ if (solAddress) {
901
+ const session = await WebSessionManager.getSession();
902
+ if (session && session.address === solAddress.address) {
903
+ const user = { provider: this, address: solAddress.address };
904
+ setCurrentUser(user);
905
+ return user;
906
+ }
907
+ }
908
+ }
909
+ // If already pending, wait for it
910
+ if (this.pendingLogin) {
911
+ return new Promise((resolve, reject) => {
912
+ this.pendingLogin.resolve = resolve;
913
+ this.pendingLogin.reject = reject;
914
+ });
915
+ }
916
+ const loginPromise = new Promise((resolve, reject) => {
917
+ this.pendingLogin = { resolve, reject };
918
+ this.loginInProgress = true;
919
+ // Always use our custom wallet modal
920
+ this.phantomMethods.showCustomModal();
921
+ // Safety timeout
922
+ setTimeout(() => {
923
+ if (this.pendingLogin) {
924
+ this.pendingLogin.reject(new Error('Login timed out'));
925
+ this.pendingLogin = null;
926
+ this.loginInProgress = false;
927
+ }
928
+ }, 180000);
929
+ });
930
+ return loginPromise.finally(() => {
931
+ this.loginOverrides = null;
932
+ });
933
+ }
934
+ async restoreSession() {
935
+ await this.ensureReady();
936
+ const session = await WebSessionManager.getSession();
937
+ if (session) {
938
+ return { provider: this, address: session.address };
939
+ }
940
+ return null;
941
+ }
942
+ // When connect is delegated to a top-level tab (openTopLevelForConnect — used
943
+ // for the cross-origin preview iframe on mobile, where MWA can't run), the
944
+ // actual connect happens in that tab and writes the session to same-origin
945
+ // storage. This watches for that session to appear and resolves the in-flight
946
+ // login() with it. It listens for `storage` events and visibility regain (the
947
+ // user returning from the tab), with a polling fallback and a hard timeout.
948
+ awaitTopLevelConnect() {
949
+ if (typeof window === 'undefined')
950
+ return;
951
+ let done = false;
952
+ const cleanup = () => {
953
+ clearInterval(poll);
954
+ clearTimeout(timeout);
955
+ window.removeEventListener('storage', onChange);
956
+ document.removeEventListener('visibilitychange', onVisible);
957
+ };
958
+ const tryResolve = async () => {
959
+ if (done)
960
+ return;
961
+ try {
962
+ const user = await this.restoreSession();
963
+ if (user && this.pendingLogin) {
964
+ done = true;
965
+ cleanup();
966
+ this.pendingLogin.resolve(user);
967
+ this.pendingLogin = null;
968
+ this.loginInProgress = false;
969
+ }
970
+ }
971
+ catch (_a) {
972
+ // not ready yet — keep waiting
973
+ }
974
+ };
975
+ const onChange = () => { void tryResolve(); };
976
+ const onVisible = () => { if (document.visibilityState === 'visible')
977
+ void tryResolve(); };
978
+ const poll = setInterval(() => { void tryResolve(); }, 1500);
979
+ const timeout = setTimeout(() => {
980
+ cleanup();
981
+ if (!done && this.pendingLogin) {
982
+ this.pendingLogin.reject(new Error('Wallet connection timed out'));
983
+ this.pendingLogin = null;
984
+ this.loginInProgress = false;
985
+ }
986
+ }, 180000);
987
+ window.addEventListener('storage', onChange);
988
+ document.addEventListener('visibilitychange', onVisible);
989
+ }
990
+ async address() {
991
+ var _a, _b, _c, _d;
992
+ await this.ensureReady();
993
+ if (!((_a = this.phantomMethods) === null || _a === void 0 ? void 0 : _a.isConnected) || !((_b = this.phantomMethods.addresses) === null || _b === void 0 ? void 0 : _b.length)) {
994
+ // Try to connect first
995
+ const user = await this.login();
996
+ if (!user)
997
+ return null;
998
+ }
999
+ const solAddress = (_d = (_c = this.phantomMethods) === null || _c === void 0 ? void 0 : _c.addresses) === null || _d === void 0 ? void 0 : _d.find((addr) => addr.addressType === phantomReactSdk.AddressType.solana);
1000
+ return (solAddress === null || solAddress === void 0 ? void 0 : solAddress.address) || null;
1001
+ }
1002
+ async runTransaction(_evmTransactionData, solTransactionData, options) {
1003
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
1004
+ if (!solTransactionData) {
1005
+ throw new Error("Solana transaction data is required for Phantom wallet");
1006
+ }
1007
+ try {
1008
+ await this.ensureSolanaReady();
1009
+ }
1010
+ catch (error) {
1011
+ console.error('Solana provider reconnection failed, logging out:', error.message);
1012
+ await this.logout();
1013
+ throw new Error('Wallet connection lost. Please reconnect.');
1014
+ }
1015
+ if (!((_a = this.phantomMethods) === null || _a === void 0 ? void 0 : _a.isConnected)) {
1016
+ const user = await this.login();
1017
+ if (!user) {
1018
+ throw new Error('Failed to connect wallet');
1019
+ }
1020
+ try {
1021
+ await this.ensureSolanaReady();
1022
+ }
1023
+ catch (error) {
1024
+ console.error('Solana provider reconnection failed after login, logging out:', error.message);
1025
+ await this.logout();
1026
+ throw new Error('Wallet connection lost. Please reconnect.');
1027
+ }
1028
+ }
1029
+ if (!((_b = this.phantomMethods) === null || _b === void 0 ? void 0 : _b.solana)) {
1030
+ throw new Error('Solana signing not available');
1031
+ }
1032
+ const rpcUrl = this.getRpcUrl(solTransactionData.network);
1033
+ const connection = new Connection(rpcUrl, 'confirmed');
1034
+ const isSurfnet = rpcUrl === SURFNET_RPC_URL;
1035
+ try {
1036
+ const remainingAccounts = convertRemainingAccounts(solTransactionData.txArgs[0].remainingAccounts);
1037
+ let app_id = solTransactionData.appId;
1038
+ if (typeof window !== 'undefined' && window.CUSTOM_TAROBASE_APP_ID_HEADER) {
1039
+ app_id = window.CUSTOM_TAROBASE_APP_ID_HEADER;
1040
+ }
1041
+ if (!app_id) {
1042
+ throw new Error("App ID is required");
1043
+ }
1044
+ // Get address
1045
+ const solAddress = this.phantomMethods.addresses.find((addr) => addr.addressType === phantomReactSdk.AddressType.solana);
1046
+ if (!solAddress) {
1047
+ throw new Error('Failed to get Solana address');
1048
+ }
1049
+ const publicKey = new PublicKey(solAddress.address);
1050
+ // Create wallet adapter using SDK methods
1051
+ const solana = this.phantomMethods.solana;
1052
+ const walletAdapter = {
1053
+ publicKey,
1054
+ signTransaction: async (tx) => {
1055
+ return await solana.signTransaction(tx);
1056
+ },
1057
+ signAllTransactions: async (txs) => {
1058
+ return await solana.signAllTransactions(txs);
1059
+ }
1060
+ };
1061
+ const anchorProvider = new anchor.AnchorProvider(connection, walletAdapter, anchor.AnchorProvider.defaultOptions());
1062
+ const finalDeduped = [];
1063
+ for (const acc of remainingAccounts) {
1064
+ const existing = finalDeduped.find((d) => d.pubkey.equals(acc.pubkey));
1065
+ if (existing) {
1066
+ existing.isSigner = existing.isSigner || acc.isSigner;
1067
+ existing.isWritable = existing.isWritable || acc.isWritable;
1068
+ }
1069
+ else {
1070
+ finalDeduped.push(acc);
1071
+ }
1072
+ }
1073
+ // When the server has co-signed a transaction (CPI attestation),
1074
+ // deserialize it and just add the wallet signature instead of
1075
+ // building from components.
1076
+ let tx;
1077
+ if (solTransactionData.signedTransaction) {
1078
+ tx = VersionedTransaction.deserialize(bufferExports.Buffer.from(solTransactionData.signedTransaction, 'base64'));
1079
+ }
1080
+ else {
1081
+ const result = await buildSetDocumentsTransaction(connection, solTransactionData.txArgs[0].idl, anchorProvider, publicKey, {
1082
+ app_id,
1083
+ documents: solTransactionData.txArgs[0].setDocumentData,
1084
+ delete_paths: solTransactionData.txArgs[0].deletePaths,
1085
+ txData: solTransactionData.txArgs[0].txData
1086
+ }, finalDeduped, solTransactionData.lutKey, solTransactionData.preInstructions, false, solTransactionData.additionalLutAddresses);
1087
+ tx = result.tx;
1088
+ }
1089
+ if ((options === null || options === void 0 ? void 0 : options.shouldSubmitTx) === false) {
1090
+ const signedTx = await walletAdapter.signTransaction(tx);
1091
+ return {
1092
+ signedTransaction: signedTx,
1093
+ blockNumber: 0,
1094
+ gasUsed: "0",
1095
+ data: ""
1096
+ };
1097
+ }
1098
+ // Keep manual submission on surfnet, use Phantom's recommended signAndSend for other networks.
1099
+ if (isSurfnet) {
1100
+ const signedTx = await walletAdapter.signTransaction(tx);
1101
+ const { signature, txInfo } = await this.submitSignedTransaction(signedTx, connection);
1102
+ return {
1103
+ transactionSignature: signature,
1104
+ blockNumber: (txInfo === null || txInfo === void 0 ? void 0 : txInfo.slot) || 0,
1105
+ gasUsed: ((_c = txInfo === null || txInfo === void 0 ? void 0 : txInfo.meta) === null || _c === void 0 ? void 0 : _c.fee.toString()) || '0',
1106
+ data: txInfo === null || txInfo === void 0 ? void 0 : txInfo.meta,
1107
+ };
1108
+ }
1109
+ const signature = await this.signAndSendViaPhantom(tx);
1110
+ const txInfo = await confirmAndCheckTransaction(connection, signature);
1111
+ return {
1112
+ transactionSignature: signature,
1113
+ blockNumber: (txInfo === null || txInfo === void 0 ? void 0 : txInfo.slot) || 0,
1114
+ gasUsed: ((_d = txInfo === null || txInfo === void 0 ? void 0 : txInfo.meta) === null || _d === void 0 ? void 0 : _d.fee.toString()) || '0',
1115
+ data: txInfo === null || txInfo === void 0 ? void 0 : txInfo.meta,
1116
+ };
1117
+ }
1118
+ catch (error) {
1119
+ // Check if this is a connection error - if so, log out
1120
+ if (((_e = error === null || error === void 0 ? void 0 : error.message) === null || _e === void 0 ? void 0 : _e.includes('not connected')) || ((_f = error === null || error === void 0 ? void 0 : error.message) === null || _f === void 0 ? void 0 : _f.includes('connect first'))) {
1121
+ console.error('Solana provider connection lost during transaction, logging out');
1122
+ await this.logout();
1123
+ throw new Error('Wallet connection lost. Please reconnect.');
1124
+ }
1125
+ const isUserRejection = (error === null || error === void 0 ? void 0 : error.code) === 4001 ||
1126
+ ((_g = error === null || error === void 0 ? void 0 : error.message) === null || _g === void 0 ? void 0 : _g.toLowerCase().includes('user rejected')) ||
1127
+ ((_h = error === null || error === void 0 ? void 0 : error.message) === null || _h === void 0 ? void 0 : _h.toLowerCase().includes('user denied')) ||
1128
+ ((_j = error === null || error === void 0 ? void 0 : error.message) === null || _j === void 0 ? void 0 : _j.toLowerCase().includes('user cancelled')) ||
1129
+ ((_k = error === null || error === void 0 ? void 0 : error.message) === null || _k === void 0 ? void 0 : _k.toLowerCase().includes('user canceled'));
1130
+ if (!isUserRejection) {
1131
+ console.error('Failed to execute transaction', error);
1132
+ }
1133
+ throw new Error(`Failed to execute transaction: ${error.message}`);
1134
+ }
1135
+ }
1136
+ /**
1137
+ * Signs a Solana transaction without submitting it.
1138
+ *
1139
+ * This method handles blockhash automatically if not set - you do NOT need to
1140
+ * set recentBlockhash on the transaction before calling this method.
1141
+ * The network/RPC URL is derived from the provider's configuration (set during initialization).
1142
+ *
1143
+ * @param transaction - The transaction to sign (Transaction or VersionedTransaction)
1144
+ * @returns The signed transaction
1145
+ */
1146
+ async signTransaction(transaction) {
1147
+ var _a, _b, _c, _d;
1148
+ try {
1149
+ await this.ensureSolanaReady();
1150
+ }
1151
+ catch (error) {
1152
+ // Reconnection failed - log user out and throw
1153
+ console.error('Solana provider reconnection failed, logging out:', error.message);
1154
+ await this.logout();
1155
+ throw new Error('Wallet connection lost. Please reconnect.');
1156
+ }
1157
+ if (!((_a = this.phantomMethods) === null || _a === void 0 ? void 0 : _a.isConnected)) {
1158
+ const user = await this.login();
1159
+ if (!user) {
1160
+ throw new Error('Failed to connect wallet');
1161
+ }
1162
+ try {
1163
+ await this.ensureSolanaReady();
1164
+ }
1165
+ catch (error) {
1166
+ console.error('Solana provider reconnection failed after login, logging out:', error.message);
1167
+ await this.logout();
1168
+ throw new Error('Wallet connection lost. Please reconnect.');
1169
+ }
1170
+ }
1171
+ if (!((_b = this.phantomMethods) === null || _b === void 0 ? void 0 : _b.solana)) {
1172
+ throw new Error('Solana signing not available');
1173
+ }
1174
+ // Use duck typing instead of instanceof to handle multiple @solana/web3.js versions
1175
+ const isLegacyTransaction = 'recentBlockhash' in transaction && !('message' in transaction && 'staticAccountKeys' in transaction.message);
1176
+ // Ensure blockhash is set before signing
1177
+ if (isLegacyTransaction) {
1178
+ const legacyTx = transaction;
1179
+ if (!legacyTx.recentBlockhash) {
1180
+ const rpcUrl = this.getRpcUrl();
1181
+ const connection = new Connection(rpcUrl, 'confirmed');
1182
+ const { blockhash, lastValidBlockHeight } = await connection.getLatestBlockhash('confirmed');
1183
+ legacyTx.recentBlockhash = blockhash;
1184
+ legacyTx.lastValidBlockHeight = lastValidBlockHeight;
1185
+ }
1186
+ // Set feePayer if not already set
1187
+ if (!legacyTx.feePayer) {
1188
+ const solAddress = this.phantomMethods.addresses.find((addr) => addr.addressType === phantomReactSdk.AddressType.solana);
1189
+ if (solAddress) {
1190
+ legacyTx.feePayer = new PublicKey(solAddress.address);
1191
+ }
1192
+ }
1193
+ }
1194
+ else {
1195
+ // VersionedTransaction
1196
+ const versionedTx = transaction;
1197
+ if (!versionedTx.message.recentBlockhash) {
1198
+ const rpcUrl = this.getRpcUrl();
1199
+ const connection = new Connection(rpcUrl, 'confirmed');
1200
+ const { blockhash } = await connection.getLatestBlockhash('confirmed');
1201
+ versionedTx.message.recentBlockhash = blockhash;
1202
+ }
1203
+ }
1204
+ try {
1205
+ return await this.phantomMethods.solana.signTransaction(transaction);
1206
+ }
1207
+ catch (error) {
1208
+ // Check if this is a connection error - if so, log out
1209
+ if (((_c = error === null || error === void 0 ? void 0 : error.message) === null || _c === void 0 ? void 0 : _c.includes('not connected')) || ((_d = error === null || error === void 0 ? void 0 : error.message) === null || _d === void 0 ? void 0 : _d.includes('connect first'))) {
1210
+ console.error('Solana provider connection lost during signing, logging out');
1211
+ await this.logout();
1212
+ throw new Error('Wallet connection lost. Please reconnect.');
1213
+ }
1214
+ throw new Error(`Failed to sign transaction: ${error.message}`);
1215
+ }
1216
+ }
1217
+ /**
1218
+ * Signs and submits a Solana transaction to the network.
1219
+ *
1220
+ * This method handles blockhash and transaction confirmation automatically - you do NOT need to
1221
+ * set recentBlockhash or lastValidBlockHeight on the transaction before calling this method.
1222
+ * The network/RPC URL is derived from the provider's configuration (set during initialization).
1223
+ *
1224
+ * @param transaction - The transaction to sign and submit (Transaction or VersionedTransaction)
1225
+ * @param feePayer - Optional fee payer public key. If not provided and the transaction doesn't
1226
+ * already have a feePayer set, the connected wallet address will be used.
1227
+ * Useful for co-signing scenarios where a different account pays the fees.
1228
+ * @returns The transaction signature
1229
+ */
1230
+ async signAndSubmitTransaction(transaction, feePayer) {
1231
+ var _a, _b, _c, _d, _e, _f, _g, _h;
1232
+ try {
1233
+ await this.ensureSolanaReady();
1234
+ }
1235
+ catch (error) {
1236
+ console.error('Solana provider reconnection failed, logging out:', error.message);
1237
+ await this.logout();
1238
+ throw new Error('Wallet connection lost. Please reconnect.');
1239
+ }
1240
+ if (!((_a = this.phantomMethods) === null || _a === void 0 ? void 0 : _a.isConnected)) {
1241
+ const user = await this.login();
1242
+ if (!user) {
1243
+ throw new Error('Failed to connect wallet');
1244
+ }
1245
+ try {
1246
+ await this.ensureSolanaReady();
1247
+ }
1248
+ catch (error) {
1249
+ console.error('Solana provider reconnection failed after login, logging out:', error.message);
1250
+ await this.logout();
1251
+ throw new Error('Wallet connection lost. Please reconnect.');
1252
+ }
1253
+ }
1254
+ if (!((_b = this.phantomMethods) === null || _b === void 0 ? void 0 : _b.solana)) {
1255
+ throw new Error('Solana signing not available');
1256
+ }
1257
+ const rpcUrl = this.getRpcUrl();
1258
+ const connection = new Connection(rpcUrl, 'confirmed');
1259
+ const isSurfnet = rpcUrl === SURFNET_RPC_URL;
1260
+ try {
1261
+ // Get fresh blockhash and set it on the transaction before signing
1262
+ const { blockhash, lastValidBlockHeight } = await connection.getLatestBlockhash('confirmed');
1263
+ // Use duck typing instead of instanceof to handle multiple @solana/web3.js versions
1264
+ const isLegacyTransaction = 'recentBlockhash' in transaction && !('message' in transaction && 'staticAccountKeys' in transaction.message);
1265
+ if (isLegacyTransaction) {
1266
+ const legacyTx = transaction;
1267
+ legacyTx.recentBlockhash = blockhash;
1268
+ legacyTx.lastValidBlockHeight = lastValidBlockHeight;
1269
+ // Set feePayer if not already set
1270
+ if (!legacyTx.feePayer) {
1271
+ if (feePayer) {
1272
+ legacyTx.feePayer = feePayer;
1273
+ }
1274
+ else {
1275
+ // Use connected wallet address as feePayer
1276
+ const solAddress = this.phantomMethods.addresses.find((addr) => addr.addressType === phantomReactSdk.AddressType.solana);
1277
+ if (solAddress) {
1278
+ legacyTx.feePayer = new PublicKey(solAddress.address);
1279
+ }
1280
+ }
1281
+ }
1282
+ }
1283
+ else {
1284
+ // VersionedTransaction
1285
+ const versionedTx = transaction;
1286
+ versionedTx.message.recentBlockhash = blockhash;
1287
+ // Note: VersionedTransaction feePayer is set in the message at creation time
1288
+ // and cannot be modified after creation
1289
+ }
1290
+ // Keep manual submission on surfnet, use Phantom's recommended signAndSend for other networks.
1291
+ if (isSurfnet) {
1292
+ const signedTx = await this.phantomMethods.solana.signTransaction(transaction);
1293
+ const { signature } = await this.submitSignedTransactionWithBlockhash(signedTx, connection, blockhash, lastValidBlockHeight);
1294
+ return signature;
1295
+ }
1296
+ const signature = await this.signAndSendViaPhantom(transaction);
1297
+ await confirmAndCheckTransaction(connection, signature);
1298
+ return signature;
1299
+ }
1300
+ catch (error) {
1301
+ // Check if this is a connection error - if so, log out
1302
+ if (((_c = error === null || error === void 0 ? void 0 : error.message) === null || _c === void 0 ? void 0 : _c.includes('not connected')) || ((_d = error === null || error === void 0 ? void 0 : error.message) === null || _d === void 0 ? void 0 : _d.includes('connect first'))) {
1303
+ console.error('Solana provider connection lost during transaction, logging out');
1304
+ await this.logout();
1305
+ throw new Error('Wallet connection lost. Please reconnect.');
1306
+ }
1307
+ const isUserRejection = (error === null || error === void 0 ? void 0 : error.code) === 4001 ||
1308
+ ((_e = error === null || error === void 0 ? void 0 : error.message) === null || _e === void 0 ? void 0 : _e.toLowerCase().includes('user rejected')) ||
1309
+ ((_f = error === null || error === void 0 ? void 0 : error.message) === null || _f === void 0 ? void 0 : _f.toLowerCase().includes('user denied')) ||
1310
+ ((_g = error === null || error === void 0 ? void 0 : error.message) === null || _g === void 0 ? void 0 : _g.toLowerCase().includes('user cancelled')) ||
1311
+ ((_h = error === null || error === void 0 ? void 0 : error.message) === null || _h === void 0 ? void 0 : _h.toLowerCase().includes('user canceled'));
1312
+ if (!isUserRejection) {
1313
+ console.error('Failed to execute transaction', error);
1314
+ }
1315
+ throw new Error(`Failed to execute transaction: ${error.message}`);
1316
+ }
1317
+ }
1318
+ async signMessage(message) {
1319
+ var _a, _b, _c, _d, _e, _f, _g, _h;
1320
+ try {
1321
+ await this.ensureSolanaReady();
1322
+ }
1323
+ catch (error) {
1324
+ // Reconnection failed - log user out and throw
1325
+ console.error('Solana provider reconnection failed, logging out:', error.message);
1326
+ await this.logout();
1327
+ throw new Error('Wallet connection lost. Please reconnect.');
1328
+ }
1329
+ if (!((_a = this.phantomMethods) === null || _a === void 0 ? void 0 : _a.isConnected)) {
1330
+ const user = await this.login();
1331
+ if (!user) {
1332
+ throw new Error('Failed to connect wallet');
1333
+ }
1334
+ try {
1335
+ await this.ensureSolanaReady();
1336
+ }
1337
+ catch (error) {
1338
+ console.error('Solana provider reconnection failed after login, logging out:', error.message);
1339
+ await this.logout();
1340
+ throw new Error('Wallet connection lost. Please reconnect.');
1341
+ }
1342
+ }
1343
+ if (!((_b = this.phantomMethods) === null || _b === void 0 ? void 0 : _b.solana)) {
1344
+ throw new Error('Solana signing not available');
1345
+ }
1346
+ try {
1347
+ // signMessage returns { signature: Uint8Array, publicKey: string }
1348
+ const result = await this.phantomMethods.solana.signMessage(message);
1349
+ return bufferExports.Buffer.from(result.signature).toString('base64');
1350
+ }
1351
+ catch (error) {
1352
+ // Check if this is a connection error - if so, log out
1353
+ if (((_c = error === null || error === void 0 ? void 0 : error.message) === null || _c === void 0 ? void 0 : _c.includes('not connected')) || ((_d = error === null || error === void 0 ? void 0 : error.message) === null || _d === void 0 ? void 0 : _d.includes('connect first'))) {
1354
+ console.error('Solana provider connection lost during signing, logging out');
1355
+ await this.logout();
1356
+ throw new Error('Wallet connection lost. Please reconnect.');
1357
+ }
1358
+ const isUserRejection = (error === null || error === void 0 ? void 0 : error.code) === 4001 ||
1359
+ ((_e = error === null || error === void 0 ? void 0 : error.message) === null || _e === void 0 ? void 0 : _e.toLowerCase().includes('user rejected')) ||
1360
+ ((_f = error === null || error === void 0 ? void 0 : error.message) === null || _f === void 0 ? void 0 : _f.toLowerCase().includes('user denied')) ||
1361
+ ((_g = error === null || error === void 0 ? void 0 : error.message) === null || _g === void 0 ? void 0 : _g.toLowerCase().includes('user cancelled')) ||
1362
+ ((_h = error === null || error === void 0 ? void 0 : error.message) === null || _h === void 0 ? void 0 : _h.toLowerCase().includes('user canceled'));
1363
+ if (!isUserRejection) {
1364
+ console.error('Failed to sign message', error);
1365
+ }
1366
+ throw new Error('Failed to sign message');
1367
+ }
1368
+ }
1369
+ async logout() {
1370
+ var _a;
1371
+ await this.ensureReady();
1372
+ try {
1373
+ if ((_a = this.phantomMethods) === null || _a === void 0 ? void 0 : _a.isConnected) {
1374
+ await this.phantomMethods.disconnect();
1375
+ }
1376
+ }
1377
+ catch (error) {
1378
+ console.error('Failed to disconnect from Phantom wallet', error);
1379
+ }
1380
+ // Always clear local state
1381
+ WebSessionManager.clearSession();
1382
+ setCurrentUser(null);
1383
+ }
1384
+ async getNativeMethods() {
1385
+ await this.ensureReady();
1386
+ return this.phantomMethods;
1387
+ }
1388
+ /* ----------------------------------------------------------- *
1389
+ * Private Helpers
1390
+ * ----------------------------------------------------------- */
1391
+ getRpcUrl(network) {
1392
+ if (this.networkUrl) {
1393
+ return this.networkUrl;
1394
+ }
1395
+ if (network === 'solana_devnet') {
1396
+ return SOLANA_DEVNET_RPC_URL;
1397
+ }
1398
+ else if (network === 'solana_mainnet') {
1399
+ return SOLANA_MAINNET_RPC_URL;
1400
+ }
1401
+ else if (network === 'surfnet') {
1402
+ return SURFNET_RPC_URL;
1403
+ }
1404
+ return SOLANA_MAINNET_RPC_URL; // default to mainnet
1405
+ }
1406
+ async signAndSendViaPhantom(transaction) {
1407
+ var _a, _b, _c;
1408
+ const result = await ((_b = (_a = this.phantomMethods) === null || _a === void 0 ? void 0 : _a.solana) === null || _b === void 0 ? void 0 : _b.signAndSendTransaction(transaction));
1409
+ const signature = (_c = result === null || result === void 0 ? void 0 : result.signature) !== null && _c !== void 0 ? _c : result === null || result === void 0 ? void 0 : result.hash;
1410
+ if (!signature) {
1411
+ throw new Error('Phantom did not return a transaction signature');
1412
+ }
1413
+ return signature;
1414
+ }
1415
+ async submitSignedTransaction(signedTx, connection) {
1416
+ // Get fresh blockhash for confirmation
1417
+ const { blockhash, lastValidBlockHeight } = await connection.getLatestBlockhash('confirmed');
1418
+ return this.submitSignedTransactionWithBlockhash(signedTx, connection, blockhash, lastValidBlockHeight);
1419
+ }
1420
+ async submitSignedTransactionWithBlockhash(signedTx, connection, blockhash, lastValidBlockHeight) {
1421
+ // Submit the transaction
1422
+ const signature = await connection.sendRawTransaction(signedTx.serialize(), {
1423
+ preflightCommitment: 'confirmed'
1424
+ });
1425
+ // Confirm using blockhash strategy (same as runTransaction)
1426
+ const confirmation = await connection.confirmTransaction({
1427
+ signature,
1428
+ blockhash,
1429
+ lastValidBlockHeight,
1430
+ }, 'confirmed');
1431
+ if (confirmation.value.err) {
1432
+ throw new Error(`Transaction failed: ${confirmation.value.err.toString()}`);
1433
+ }
1434
+ // Get transaction info
1435
+ const txInfo = await connection.getParsedTransaction(signature, {
1436
+ maxSupportedTransactionVersion: 0,
1437
+ commitment: 'confirmed'
1438
+ });
1439
+ return { signature, txInfo };
1440
+ }
1441
+ }
1442
+ PhantomWalletProvider.instance = null;
1443
+
1444
+ export { PhantomWalletProvider };
1445
+ //# sourceMappingURL=phantom-wallet-provider-DMlaSrAl.esm.js.map