import type { NetworkId, Namespace } from '@meshconnect/uwc-types' /** * Parse a WalletConnect account string into its components * Account format: "namespace:chainId:address" * Example: "eip155:1:0x1234..." or "solana:mainnet:ABC123..." */ export function parseAccount(account: string): { namespace: Namespace chainId: string networkId: NetworkId address: string } { const parts = account.split(':') if (parts.length < 3) { throw new Error(`Invalid account format: ${account}`) } const namespace = parts[0] as Namespace const chainId = parts[1]! const networkId = `${namespace}:${chainId}` as NetworkId // Handle addresses that might contain colons (like some Solana addresses) const address = parts.slice(2).join(':') return { namespace, chainId, networkId, address } } /** * Build a WalletConnect account string from components */ export function buildAccount( namespace: Namespace, chainId: string, address: string ): string { return `${namespace}:${chainId}:${address}` } /** * Extract namespace from a network ID * Example: "eip155:1" -> "eip155" */ export function getNamespaceFromNetworkId(networkId: NetworkId): Namespace { const [namespace] = networkId.split(':') return namespace as Namespace } /** * Extract chain ID from a network ID * Example: "eip155:1" -> "1" */ export function getChainIdFromNetworkId(networkId: NetworkId): string { const [, chainId] = networkId.split(':') return chainId || '' } /** * Find an account in session namespaces that matches the given network and address */ export function findAccountInNamespaces( namespaces: Record, targetNetworkId: NetworkId, targetAddress: string ): string | null { for (const [, namespaceData] of Object.entries(namespaces)) { for (const account of namespaceData.accounts || []) { const { networkId, address } = parseAccount(account) if (networkId === targetNetworkId && address === targetAddress) { return account } } } return null } /** * Extract all accounts from session namespaces */ export function extractAccountsFromNamespaces( namespaces: Record ): Array<{ account: string namespace: Namespace chainId: string networkId: NetworkId address: string }> { const accounts: Array<{ account: string namespace: Namespace chainId: string networkId: NetworkId address: string }> = [] Object.entries(namespaces).forEach(([, namespaceData]) => { ;(namespaceData.accounts || []).forEach((account: string) => { try { const parsed = parseAccount(account) accounts.push({ account, ...parsed }) } catch { // Skip invalid accounts } }) }) return accounts }