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