import type { NetworkId, AvailableAddress, EVMCapabilities, EVMCapabilityStatus, Network, WalletMetadata, WalletLifecycleEvent } from '@meshconnect/uwc-types' import type { EthereumProvider, DetectedWallet as EIP6963DetectedWallet } from '../../eip6963-discovery' import { getAvailableWallets as getEIP6963Wallets } from '../../eip6963-discovery' import { supportedNetworks } from '@meshconnect/uwc-constants' /** * Normalize an EIP-1193 `chainChanged` payload (hex `'0x1'`, decimal string, or a * number) to a CAIP-2 id. Returns undefined for an unparseable value rather than * emitting a bogus chain id. */ function toCaipChainId(raw: unknown): NetworkId | undefined { let decimal: number | undefined if (typeof raw === 'string') { // Validate the FULL string before converting: parseInt('0x1junk', 16) === 1, // which would emit a bogus chain id instead of undefined. if (/^0x[0-9a-fA-F]+$/.test(raw)) { decimal = parseInt(raw, 16) } else if (/^\d+$/.test(raw)) { decimal = parseInt(raw, 10) } } else if (typeof raw === 'number' && Number.isInteger(raw) && raw >= 0) { decimal = raw } // isSafeInteger: beyond 2^53-1 parseInt has already lost precision (and a // ~256-nibble hex overflows to Infinity) — emitting a silently-wrong chain // id is worse than emitting none. return decimal !== undefined && Number.isSafeInteger(decimal) ? (`eip155:${decimal}` as NetworkId) : undefined } /** * Service for managing Ethereum wallet connections */ export class EthereumWalletService { private detectedWallets: EIP6963DetectedWallet[] = [] private connectedProvider: EthereumProvider | null = null private account: string | null = null /** * Initialize wallet discovery */ async initializeDiscovery(expectedWallets?: WalletMetadata[]): Promise { this.detectedWallets = await getEIP6963Wallets(expectedWallets) } /** * Get detected wallets */ getDetectedWallets(): EIP6963DetectedWallet[] { return this.detectedWallets } /** * Find wallet by UUID */ findWalletByUuid(uuid: string): EIP6963DetectedWallet | undefined { return this.detectedWallets.find(w => w.uuid === uuid) } /** * Check if a wallet is already connected without requesting access */ async checkExistingConnection( provider: EthereumProvider ): Promise { try { // Try eth_accounts which doesn't prompt user const accounts = await provider.request({ method: 'eth_accounts' }) return accounts && accounts.length > 0 ? accounts : null } catch { return null } } /** * Connect to wallet */ async connect(provider: EthereumProvider): Promise { const accounts = await provider.request({ method: 'eth_requestAccounts' }) if (!accounts || accounts.length === 0) { throw new Error('No accounts returned from wallet') } const address = accounts[0] this.connectedProvider = provider this.account = address // Request chain ID to ensure we're connected await provider.request({ method: 'eth_chainId' }) return address } /** * Helper function to get network data by network ID */ getNetworkById(networkId: NetworkId): Network | undefined { return supportedNetworks.find( (network: Network) => network.id === networkId ) } /** * Switch network */ async switchNetwork( networkId: string, supportsAddingNetworks?: boolean | null | undefined ): Promise { if (!this.connectedProvider) { throw new Error('No Ethereum wallet connected') } // Extract chain ID from network.id (format: "eip155:1") const chainIdParts = networkId.split(':') if (chainIdParts.length !== 2 || !chainIdParts[1]) { throw new Error(`Invalid network ID format: ${networkId}`) } const chainId = chainIdParts[1] const chainIdHex = `0x${parseInt(chainId, 10).toString(16)}` // Try to switch to the requested chain try { await this.connectedProvider.request({ method: 'wallet_switchEthereumChain', params: [{ chainId: chainIdHex }] }) } catch (switchError: unknown) { // This error code indicates that the chain has not been added to the wallet if ( (switchError as { code?: number }).code === 4902 && (supportsAddingNetworks ?? true) ) { // Try to add the chain to the wallet try { const network = this.getNetworkById(networkId as NetworkId) if (!network) { throw new Error( `Network with id ${networkId} not found or not supported` ) } await this.connectedProvider.request({ method: 'wallet_addEthereumChain', params: [ { chainId: chainIdHex, chainName: network.name, nativeCurrency: network.nativeCurrency, rpcUrls: network.rpcUrls?.default.http, blockExplorerUrls: [network.blockExplorers?.default.url] } ] }) await this.connectedProvider.request({ method: 'wallet_switchEthereumChain', params: [{ chainId: chainIdHex }] }) } catch (addError: unknown) { let errorMessage: string if (addError instanceof Error) { errorMessage = addError.message } else if ( typeof addError === 'object' && addError !== null && 'message' in addError ) { errorMessage = String(addError.message) } else { errorMessage = String(addError) } throw new Error( `Chain ${networkId} cannot be added to the wallet: Error: ${errorMessage}` ) } } throw switchError } } /** * Build available addresses for all supported networks */ buildAvailableAddresses( supportedNetworkIds: string[], address: string ): AvailableAddress[] { const addresses: AvailableAddress[] = [] supportedNetworkIds.forEach(networkId => { if (networkId.startsWith('eip155:')) { addresses.push({ address, networkId: networkId as NetworkId }) } }) return addresses } /** * Set connection state */ setConnectionState( provider: EthereumProvider | null, account: string | null ): void { this.connectedProvider = provider this.account = account } /** * Get current account */ getAccount(): string | null { return this.account } /** * Get connected provider */ getConnectedProvider(): EthereumProvider | null { return this.connectedProvider } /** * Subscribe to the live EIP-1193 provider's lifecycle events (account/chain * switched in the wallet, disconnect). Returns a teardown, or `undefined` when * there is no connected provider or it lacks `.on`/`.removeListener` (EIP-1193 * lists removeListener as SHOULD — attaching listeners we could never remove * would BE the zombie-listener class this layer exists to prevent). * * PII boundary: the new address from `accountsChanged` is NEVER forwarded — an * empty account list maps to `disconnect`, a non-empty one to a content-free * `accountChanged`. `chainChanged` carries only the (non-PII) CAIP-2 chain id. */ onLifecycleEvent( listener: (event: WalletLifecycleEvent) => void ): (() => void) | undefined { const provider = this.connectedProvider if ( !provider || typeof provider.on !== 'function' || typeof provider.removeListener !== 'function' ) { return undefined } // In the production iframe the connected provider is a Comlink proxy across // the bridge: an un-proxied EIP-1193 handler can't be cloned over postMessage, // and `on`/`removeListener` can't satisfy teardown across the bridge (callback // identity). Subscribing here would throw or leak a listener. Until the bridge // exposes a forwarding wrapper (P3), report lifecycle as unavailable over the // bridge (the core emits `lifecycleTelemetryUnavailable`) rather than // attempting a broken subscription. if ( typeof window !== 'undefined' && (window as unknown as { UWCBridgeChildInitialized?: boolean }) .UWCBridgeChildInitialized === true ) { return undefined } const onAccounts = (accounts: unknown) => { const list = Array.isArray(accounts) ? accounts : [] listener( list.length === 0 ? { type: 'disconnect' } : { type: 'accountChanged' } ) } const onChain = (chainId: unknown) => { const caip = toCaipChainId(chainId) listener( caip !== undefined ? { type: 'chainChanged', chainId: caip } : { type: 'chainChanged' } ) } const onDisconnect = () => listener({ type: 'disconnect' }) provider.on('accountsChanged', onAccounts) provider.on('chainChanged', onChain) provider.on('disconnect', onDisconnect) return () => { provider.removeListener?.('accountsChanged', onAccounts) provider.removeListener?.('chainChanged', onChain) provider.removeListener?.('disconnect', onDisconnect) } } /** * Disconnect (clear state only) */ disconnect(): void { this.connectedProvider = null this.account = null } /** * Get wallet capabilities (EIP-5792 support) */ async getCapabilities( from: string, networks: Network[] ): Promise> { if (!this.connectedProvider) { throw new Error('No Ethereum wallet connected') } // eslint-disable-next-line @typescript-eslint/no-explicit-any let raw: Record<`0x${string}`, Record> try { const availableNetworkIds = networks .filter(network => network.networkType === 'evm') .map(network => `0x${network.internalId.toString(16)}`) const timeoutPromise = new Promise((_, reject) => { setTimeout(() => { reject(new Error('wallet_getCapabilities timed out after 3 seconds')) }, 3000) }) const requestPromise = this.connectedProvider.request({ method: 'wallet_getCapabilities', params: [from, availableNetworkIds] }) raw = await Promise.race([requestPromise, timeoutPromise]) } catch { return {} } const result: Record = {} for (const [chainId, caps] of Object.entries(raw || {})) { const networkId = `eip155:${Number(chainId)}` result[networkId] = {} for (const [capKey, capValue] of Object.entries(caps)) { if (capValue && typeof capValue === 'object') { if (typeof capValue.supported === 'boolean') { result[networkId][capKey as keyof EVMCapabilities] = { status: capValue.supported ? 'supported' : 'unsupported' } } else if ( typeof capValue.status === 'string' && ['supported', 'ready', 'unsupported'].includes(capValue.status) ) { result[networkId][capKey as keyof EVMCapabilities] = { status: capValue.status as EVMCapabilityStatus } } } } } return result } }