@bounded-sh/client 0.0.25 → 0.0.27

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