import { browser } from 'wxt/browser'; import type { NexaMessage } from '@/shared/messaging'; import { callWallet } from './wallet-bridge/relay'; import { hideConnectBanner, setConnectBannerError, showConnectBanner } from './wallet-bridge/banner'; interface ConnectResult { walletAddress: string; } interface SignResult { signature: string; } async function reportConnected(walletAddress: string): Promise { hideConnectBanner(); await browser.runtime .sendMessage({ type: 'nexa:wallet-connected', walletAddress } satisfies NexaMessage) .catch(() => undefined); } /** Real user gesture (banner button click) — required for Phantom to show its connect approval popup on a first-ever connect. */ async function connectWithGesture(): Promise { try { const { walletAddress } = await callWallet('connect', {}); await reportConnected(walletAddress); } catch (err) { setConnectBannerError(err instanceof Error ? err.message : String(err)); } } /** * `onlyIfTrusted` succeeds without any user interaction if this origin was * already approved in a previous session — the normal case after the first * connect. Falls back to the on-page banner (a real click) only when it isn't. */ async function attemptSilentConnect(): Promise { try { const { walletAddress } = await callWallet('connect', { onlyIfTrusted: true }); await reportConnected(walletAddress); } catch { showConnectBanner(() => void connectWithGesture()); } } /** Wires wallet connect/sign into the page. Independent of any site adapter — runs regardless of whether a buy-button adapter matched. */ export function initWalletConnect(): void { void attemptSilentConnect(); browser.runtime.onMessage.addListener((message: NexaMessage, _sender, sendResponse) => { if (message?.type === 'nexa:wallet-sign-request') { callWallet('signMessage', { message: message.nonce }) .then((result) => sendResponse(result)) .catch((err) => sendResponse({ error: err instanceof Error ? err.message : String(err) })); return true; } if (message?.type === 'nexa:request-wallet-connect') { void attemptSilentConnect(); return false; } return undefined; }); }