@kheopskit/core 6.0.0-rc.4 → 6.0.0-rc.6

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 (40) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/dist/ethereum.d.mts +1 -1
  3. package/dist/ethereum.d.ts +1 -1
  4. package/dist/index.d.mts +2 -2
  5. package/dist/index.d.ts +2 -2
  6. package/dist/index.js +1 -1
  7. package/dist/index.mjs +1 -1
  8. package/dist/{instance-D6rAcYlp.d.ts → instance-1BgEld17.d.ts} +2 -2
  9. package/dist/{instance-DN64bXb6.mjs → instance-BPAvq0v7.mjs} +18 -7
  10. package/dist/instance-BPAvq0v7.mjs.map +1 -0
  11. package/dist/{instance-ClNA6MX-.js → instance-CCP7uJV3.js} +17 -6
  12. package/dist/instance-CCP7uJV3.js.map +1 -0
  13. package/dist/{instance-DTxZT9GE.d.mts → instance-DDvZiq1L.d.mts} +2 -2
  14. package/dist/internal.d.mts +2 -2
  15. package/dist/internal.d.ts +2 -2
  16. package/dist/internal.js +1 -1
  17. package/dist/internal.mjs +1 -1
  18. package/dist/polkadot.d.mts +14 -1
  19. package/dist/polkadot.d.ts +14 -1
  20. package/dist/polkadot.js +8 -4
  21. package/dist/polkadot.js.map +1 -1
  22. package/dist/polkadot.mjs +8 -4
  23. package/dist/polkadot.mjs.map +1 -1
  24. package/dist/solana.d.mts +1 -1
  25. package/dist/solana.d.ts +1 -1
  26. package/dist/testing.d.mts +1 -1
  27. package/dist/testing.d.ts +1 -1
  28. package/dist/{types-C7DyeFOY.d.ts → types-BGeGUtxz.d.mts} +2 -3
  29. package/dist/{types-C7DyeFOY.d.mts → types-BGeGUtxz.d.ts} +2 -3
  30. package/dist/types-BrMtrjs9.js.map +1 -1
  31. package/dist/types-D7OWi0Td.mjs.map +1 -1
  32. package/dist/walletconnect.d.mts +1 -1
  33. package/dist/walletconnect.d.ts +1 -1
  34. package/dist/walletconnect.js +13 -8
  35. package/dist/walletconnect.js.map +1 -1
  36. package/dist/walletconnect.mjs +13 -8
  37. package/dist/walletconnect.mjs.map +1 -1
  38. package/package.json +1 -1
  39. package/dist/instance-ClNA6MX-.js.map +0 -1
  40. package/dist/instance-DN64bXb6.mjs.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"instance-CCP7uJV3.js","names":["KheopskitError","POLKADOT_EXTENSIONS","walletPendingError","parseWalletId","isWalletConnectWallet","PLATFORM_ORDER","isWalletConnectWallet","map","take","switchMap","scan","distinctUntilChanged","isEqual","isInjectedWallet","map","Observable","Subscription","BehaviorSubject","timer","startWith","combineLatest","filter","take","tap","Observable","framesOf","map","isWalletConnectWallet","combineLatest","of","shareReplay","BehaviorSubject","Observable","isValidWalletId","WALLET_CONNECT_WALLET_ID","parseWalletId","isWalletPlatform","getWalletAccountId","isValidWalletId","isWalletPlatform","uniq","Observable","combineLatest","map","of","startWith","isInjectedWallet","KheopskitError","withLatestFrom","filter","mergeMap","tap","shareReplay","Observable","abortedError","walletPendingError","isInjectedWallet","createRegistryReads$","shareReplay","map","concat","of","ignoreElements","EMPTY","take","combineLatest","startWith","debounceTime","asapScheduler","distinctUntilChanged","tap","filter","isWalletConnectWallet","KheopskitError","Observable","defer","share","ReplaySubject","parseWalletAccountId","KheopskitError","accountUnavailableError","map"],"sources":["../src/api/config.ts","../src/utils/hydrateState.ts","../src/utils/storage.ts","../src/utils/iconCache.ts","../src/utils/sortAccounts.ts","../src/utils/sortWallets.ts","../src/api/platform.ts","../src/api/reconnectPolicy.ts","../src/api/hydration.ts","../src/utils/createHydrationBuffer.ts","../src/utils/logObservable.ts","../src/api/accounts.ts","../src/utils/createStore.ts","../src/api/compactStore.ts","../src/api/store.ts","../src/api/wallets.ts","../src/api/kheopskit.ts","../src/api/liveActions.ts","../src/api/livePipeline.ts","../src/api/instance.ts"],"sourcesContent":["import { KheopskitError } from \"./errors\";\nimport type { KheopskitConfig, KheopskitPlatform } from \"./types\";\n\n/**\n * Default storage key for persisting wallet connection state.\n * Can be overridden via config.storageKey to avoid conflicts\n * when running multiple dapps on the same domain.\n */\nexport const DEFAULT_STORAGE_KEY = \"kheopskit\";\n\nconst DEFAULTS = {\n\tautoReconnect: true,\n\tdebug: false,\n\tstorageKey: DEFAULT_STORAGE_KEY,\n\thydrationGracePeriod: 500,\n\thydrationTimeout: 3000,\n} satisfies Omit<KheopskitConfig, \"platforms\" | \"walletConnect\">;\n\nexport const resolveConfig = <\n\tconst P extends readonly KheopskitPlatform[] = readonly KheopskitPlatform[],\n>(\n\tconfig?: Partial<KheopskitConfig<P>>,\n): KheopskitConfig<P> => {\n\tconst platforms = (config?.platforms ?? []) as P;\n\n\t// Guard the v4 breaking change: platforms are plugin instances, not strings.\n\t// Catches JS callers (no tsc) and gives agents a fix that names the doc.\n\tconst invalidPlatforms = (platforms as readonly unknown[]).filter(\n\t\t(p) =>\n\t\t\ttypeof p !== \"object\" ||\n\t\t\tp === null ||\n\t\t\ttypeof (p as { getWallets$?: unknown }).getWallets$ !== \"function\",\n\t);\n\tif (invalidPlatforms.length > 0) {\n\t\tthrow new Error(\n\t\t\t\"[kheopskit] config.platforms must contain plugin instances created by the \" +\n\t\t\t\t\"per-platform factories (e.g. platforms: [polkadot(), ethereum(), solana()] \" +\n\t\t\t\t'imported from \"@kheopskit/core/<platform>\"). ' +\n\t\t\t\t`Invalid entries: ${JSON.stringify(invalidPlatforms)}. ` +\n\t\t\t\t'String platform names like \"polkadot\" were removed in v4 — see MIGRATING_TO_V4.md.',\n\t\t);\n\t}\n\n\tif (\n\t\tconfig?.walletConnect !== undefined &&\n\t\ttypeof (config.walletConnect as { getWallet$?: unknown } | null)\n\t\t\t?.getWallet$ !== \"function\"\n\t) {\n\t\tthrow new KheopskitError(\n\t\t\t\"INVALID_CONFIG\",\n\t\t\t\"config.walletConnect must be created by walletConnect() imported from \" +\n\t\t\t\t'\"@kheopskit/core/walletconnect\", e.g. walletConnect: walletConnect({ projectId, metadata, networks }). ' +\n\t\t\t\t\"Raw WalletConnect options were removed in v6, see MIGRATING_TO_V6.md.\",\n\t\t);\n\t}\n\n\tif (platforms.length === 0) {\n\t\tconsole.warn(\n\t\t\t\"[kheopskit] No platforms configured; wallets and accounts will be empty. \" +\n\t\t\t\t'Pass e.g. platforms: [polkadot()] from \"@kheopskit/core/polkadot\".',\n\t\t);\n\t}\n\n\treturn Object.assign({}, DEFAULTS, config, { platforms });\n};\n","import { walletPendingError } from \"../api/errors\";\nimport {\n\ttype BaseWallet,\n\ttype BaseWalletAccount,\n\ttype CachedAccount,\n\ttype CachedWallet,\n\tisWalletConnectWallet,\n\ttype PolkadotAccountType,\n\ttype WalletConnectWallet,\n} from \"../api/types\";\nimport { POLKADOT_EXTENSIONS } from \"./polkadotExtensions\";\nimport type { WalletAccountId } from \"./WalletAccountId\";\nimport { parseWalletId, type WalletId } from \"./WalletId\";\n\n/**\n * Looks up the icon for a wallet from known Polkadot extensions only.\n * Ethereum icons will be populated from the localStorage icon cache via the merge function.\n *\n * Note: We DON'T use localStorage icon cache here because hydrateWallet is called\n * during SSR (server) and client hydration. localStorage isn't available on server,\n * so using it would cause a hydration mismatch. Icons for Ethereum wallets will be\n * populated when the hydration buffer merges cached wallets with live wallets.\n */\nconst lookupWalletIcon = (platform: string, identifier: string): string => {\n\t// Only Polkadot extensions have hardcoded icons that are safe for SSR\n\tif (platform === \"polkadot\") {\n\t\treturn POLKADOT_EXTENSIONS[identifier]?.icon ?? \"\";\n\t}\n\t// Ethereum icons come from localStorage or live wallets - not here\n\treturn \"\";\n};\n\ntype PlaceholderOf<W> = W & { isPlaceholder: true; isConnected: false };\n\nexport const hydrateWallet = (\n\tcached: CachedWallet,\n): PlaceholderOf<BaseWallet | WalletConnectWallet> => {\n\tconst connect = async () => {\n\t\tthrow walletPendingError(cached.id);\n\t};\n\tconst disconnect = async () => {};\n\n\tif (cached.type === \"walletconnect\") {\n\t\treturn {\n\t\t\tid: cached.id,\n\t\t\ttype: \"walletconnect\",\n\t\t\tplatforms: [],\n\t\t\tname: cached.name,\n\t\t\ticon: \"\",\n\t\t\tstatus: cached.isConnected ? \"connecting\" : \"disconnected\",\n\t\t\tisPlaceholder: true,\n\t\t\tisConnected: false,\n\t\t\tconnect,\n\t\t\tdisconnect,\n\t\t};\n\t}\n\n\tconst { platform, identifier } = parseWalletId(cached.id);\n\n\treturn {\n\t\tid: cached.id,\n\t\tplatform: cached.platform as BaseWallet[\"platform\"],\n\t\ttype: cached.type,\n\t\tname: cached.name,\n\t\ticon: lookupWalletIcon(platform, identifier),\n\t\tstatus: cached.isConnected ? \"connecting\" : \"disconnected\",\n\t\tisPlaceholder: true,\n\t\tisConnected: false,\n\t\tconnect,\n\t\tdisconnect,\n\t};\n};\n\nexport const hydrateAccount = (\n\tcached: CachedAccount,\n): BaseWalletAccount & { isPlaceholder: true } => ({\n\tid: cached.id as WalletAccountId,\n\tisPlaceholder: true,\n\tplatform: cached.platform,\n\taddress: cached.address,\n\tname: cached.name,\n\twalletId: cached.walletId,\n\twalletName: cached.walletName,\n\t// Spread (not direct keys) so the extra platform fields don't trip the\n\t// excess-property check against BaseWalletAccount; they're read back via the\n\t// platform-specific account types once narrowed by `platform`.\n\t...(cached.platform === \"ethereum\" && { chainId: cached.chainId }),\n\t...(cached.platform === \"polkadot\" && {\n\t\ttype: cached.polkadotAccountType,\n\t}),\n\t...(cached.platform === \"solana\" && { chains: [] }),\n});\n\n/**\n * Converts a wallet to a CachedWallet for storage.\n * Only extracts the serializable properties needed for hydration.\n */\nexport const serializeWallet = (\n\twallet: BaseWallet | WalletConnectWallet,\n): CachedWallet => ({\n\tid: wallet.id,\n\t// The WalletConnect connector has no platform.\n\tplatform: isWalletConnectWallet(wallet) ? undefined : wallet.platform,\n\ttype: wallet.type,\n\tname: wallet.name,\n\t// Note: icon is NOT stored to save cookie space\n\tisConnected: wallet.isConnected,\n});\n\n/**\n * Converts an account to a CachedAccount for storage.\n * Only extracts the serializable properties needed for hydration. Platform-only\n * fields (Ethereum chainId, Polkadot key type) are read defensively so this\n * stays SDK-free.\n */\nexport const serializeAccount = (\n\taccount: BaseWalletAccount,\n): CachedAccount => ({\n\tid: account.id,\n\tplatform: account.platform,\n\taddress: account.address,\n\tname: account.name,\n\tchainId:\n\t\taccount.platform === \"ethereum\"\n\t\t\t? (account as { chainId?: number }).chainId\n\t\t\t: undefined,\n\tpolkadotAccountType:\n\t\taccount.platform === \"polkadot\"\n\t\t\t? (account as { type?: PolkadotAccountType }).type\n\t\t\t: undefined,\n\twalletId: account.walletId as WalletId,\n\twalletName: account.walletName,\n});\n","export type Storage = {\n\tgetItem: (key: string) => string | null;\n\tsetItem: (key: string, value: string) => void;\n\tremoveItem: (key: string) => void;\n};\n\n/**\n * Extended storage interface with cross-tab sync support.\n */\nexport type SyncableStorage = Storage & {\n\t/**\n\t * Subscribe to storage changes from other tabs.\n\t * Returns an unsubscribe function.\n\t */\n\tsubscribe?: (\n\t\tkey: string,\n\t\tcallback: (value: string | null) => void,\n\t) => () => void;\n};\n\n/**\n * A no-op storage implementation that does nothing.\n * Useful for testing or SSR environments where no storage is needed.\n */\nexport const noopStorage: SyncableStorage = {\n\tgetItem: () => null,\n\tsetItem: () => {},\n\tremoveItem: () => {},\n};\n\n/**\n * Cached localStorage wrapper instance.\n * Lazily initialized on first access to avoid SSR issues.\n */\nlet _safeLocalStorage: SyncableStorage | null = null;\n\n/**\n * Creates the localStorage wrapper, testing for availability.\n * Returns noopStorage if localStorage is unavailable (SSR, private browsing, etc.)\n */\nconst createSafeLocalStorage = (): SyncableStorage => {\n\tif (typeof window === \"undefined\") return noopStorage;\n\n\ttry {\n\t\t// Test that localStorage is accessible (may throw in private browsing)\n\t\tconst testKey = \"__kheopskit_test__\";\n\t\twindow.localStorage.setItem(testKey, testKey);\n\t\twindow.localStorage.removeItem(testKey);\n\n\t\treturn {\n\t\t\tgetItem: (key: string) => window.localStorage.getItem(key),\n\t\t\tsetItem: (key: string, value: string) =>\n\t\t\t\twindow.localStorage.setItem(key, value),\n\t\t\tremoveItem: (key: string) => window.localStorage.removeItem(key),\n\t\t\tsubscribe: (key: string, callback: (value: string | null) => void) => {\n\t\t\t\tconst handler = (event: StorageEvent) => {\n\t\t\t\t\tif (event.key === key) {\n\t\t\t\t\t\tcallback(event.newValue);\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t\twindow.addEventListener(\"storage\", handler);\n\t\t\t\treturn () => window.removeEventListener(\"storage\", handler);\n\t\t\t},\n\t\t};\n\t} catch {\n\t\treturn noopStorage;\n\t}\n};\n\n/**\n * A safe localStorage wrapper that falls back to noopStorage\n * when localStorage is not available (e.g., during SSR).\n * Includes cross-tab sync via the native 'storage' event.\n *\n * Lazily initialized on first access to be SSR-safe.\n */\nexport const getSafeLocalStorage = (): SyncableStorage => {\n\tif (_safeLocalStorage === null) {\n\t\t_safeLocalStorage = createSafeLocalStorage();\n\t}\n\treturn _safeLocalStorage;\n};\n\n/**\n * @deprecated Use getSafeLocalStorage() instead. This is kept for backward compatibility.\n * Returns a proxy that lazily initializes on first use.\n */\nexport const safeLocalStorage: SyncableStorage = {\n\tgetItem: (key: string) => getSafeLocalStorage().getItem(key),\n\tsetItem: (key: string, value: string) =>\n\t\tgetSafeLocalStorage().setItem(key, value),\n\tremoveItem: (key: string) => getSafeLocalStorage().removeItem(key),\n\tget subscribe() {\n\t\treturn getSafeLocalStorage().subscribe;\n\t},\n};\n\n/**\n * Parse a cookie string to extract the value for a specific key.\n * @param cookieString - The full cookie header string (e.g., document.cookie or req.headers.cookie)\n * @param key - The cookie key to find\n * @returns The cookie value or null if not found\n */\nexport const parseCookie = (\n\tcookieString: string | undefined,\n\tkey: string,\n): string | null => {\n\tif (!cookieString) return null;\n\n\tfor (const cookie of cookieString.split(\";\")) {\n\t\tconst [k, ...v] = cookie.split(\"=\");\n\t\tconst cookieKey = k?.trim();\n\t\tif (cookieKey === key) {\n\t\t\ttry {\n\t\t\t\treturn decodeURIComponent(v.join(\"=\").trim());\n\t\t\t} catch {\n\t\t\t\treturn null; // Malformed cookie value\n\t\t\t}\n\t\t}\n\t}\n\n\treturn null;\n};\n\n/**\n * Maximum recommended size for cookie storage (3KB to stay well under 4KB limit).\n *\n * @remarks\n * Cookie storage is subject to browser limits (typically 4KB per cookie).\n * When users connect many wallets, the auto-reconnect list may exceed this limit.\n * If this happens:\n * - A console warning will be logged\n * - Some browsers may silently reject the cookie\n * - Consider using fewer simultaneous wallet connections\n *\n * The stored data includes wallet IDs in format `platform:identifier`\n * (e.g., `polkadot:talisman`, `ethereum:io.metamask`).\n */\nexport const COOKIE_MAX_SIZE = 3 * 1024;\n\n/**\n * BroadcastChannel name for cross-tab cookie sync.\n */\nconst BROADCAST_CHANNEL_NAME = \"kheopskit-storage-sync\";\n\n/**\n * Singleton BroadcastChannel for cross-tab cookie sync.\n * Created once and shared across all cookieStorage instances.\n */\nlet sharedBroadcastChannel: BroadcastChannel | null = null;\n\nconst getBroadcastChannel = (): BroadcastChannel | null => {\n\tif (sharedBroadcastChannel) return sharedBroadcastChannel;\n\tif (typeof BroadcastChannel === \"undefined\") return null;\n\n\ttry {\n\t\tsharedBroadcastChannel = new BroadcastChannel(BROADCAST_CHANNEL_NAME);\n\t} catch {\n\t\t// BroadcastChannel not supported or failed\n\t}\n\treturn sharedBroadcastChannel;\n};\n\n/**\n * Check if the current connection is secure (HTTPS).\n * Must be called at runtime (inside methods) to work correctly after SSR hydration.\n */\nconst isSecureConnection = (): boolean =>\n\ttypeof window !== \"undefined\" && window.location.protocol === \"https:\";\n\n/**\n * A cookie-based storage implementation for SSR environments.\n * Reads cookies from an optional initial cookie string (for SSR hydration),\n * writes to document.cookie on the client.\n *\n * Features:\n * - Secure flag automatically added for HTTPS connections\n * - Cross-tab synchronization via BroadcastChannel API\n * - Size limit warning when data exceeds recommended limits\n *\n * @param initialCookies - Optional cookie string for server-side hydration\n */\nexport const cookieStorage = (initialCookies?: string): SyncableStorage => {\n\treturn {\n\t\tgetItem: (key: string) => {\n\t\t\t// On server, use initialCookies. On client, read from document.cookie\n\t\t\tconst cookieString =\n\t\t\t\ttypeof document !== \"undefined\" ? document.cookie : initialCookies;\n\t\t\treturn parseCookie(cookieString, key);\n\t\t},\n\t\tsetItem: (key: string, value: string) => {\n\t\t\tif (typeof document === \"undefined\") return;\n\n\t\t\t// Warn if value exceeds recommended size\n\t\t\tconst encodedValue = encodeURIComponent(value);\n\t\t\tif (encodedValue.length > COOKIE_MAX_SIZE) {\n\t\t\t\tconsole.warn(\n\t\t\t\t\t`[kheopskit] Cookie value for \"${key}\" exceeds recommended size limit (${encodedValue.length} > ${COOKIE_MAX_SIZE} bytes). ` +\n\t\t\t\t\t\t\"This may cause issues with cookie storage. Consider reducing the number of connected wallets.\",\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// Set cookie with 1 year expiry\n\t\t\tconst expires = new Date();\n\t\t\texpires.setFullYear(expires.getFullYear() + 1);\n\n\t\t\t// Build cookie string with security attributes\n\t\t\tlet cookieStr = `${key}=${encodedValue};expires=${expires.toUTCString()};path=/;SameSite=Lax`;\n\t\t\tif (isSecureConnection()) {\n\t\t\t\tcookieStr += \";Secure\";\n\t\t\t}\n\n\t\t\t// biome-ignore lint: necessary for cookie storage - direct cookie assignment is the standard API\n\t\t\tdocument.cookie = cookieStr;\n\n\t\t\t// Broadcast change to other tabs\n\t\t\tgetBroadcastChannel()?.postMessage({ type: \"set\", key, value });\n\t\t},\n\t\tremoveItem: (key: string) => {\n\t\t\tif (typeof document === \"undefined\") return;\n\n\t\t\t// Build delete cookie string\n\t\t\tlet cookieStr = `${key}=;expires=Thu, 01 Jan 1970 00:00:01 GMT;path=/;SameSite=Lax`;\n\t\t\tif (isSecureConnection()) {\n\t\t\t\tcookieStr += \";Secure\";\n\t\t\t}\n\n\t\t\t// biome-ignore lint: necessary for cookie storage - direct cookie assignment is the standard API\n\t\t\tdocument.cookie = cookieStr;\n\n\t\t\t// Broadcast change to other tabs\n\t\t\tgetBroadcastChannel()?.postMessage({ type: \"remove\", key });\n\t\t},\n\t\tsubscribe: (key: string, callback: (value: string | null) => void) => {\n\t\t\tconst channel = getBroadcastChannel();\n\t\t\tif (!channel) return () => {};\n\n\t\t\tconst handler = (event: MessageEvent) => {\n\t\t\t\tconst data = event.data as {\n\t\t\t\t\ttype: string;\n\t\t\t\t\tkey: string;\n\t\t\t\t\tvalue?: string;\n\t\t\t\t};\n\t\t\t\tif (data.key === key) {\n\t\t\t\t\tif (data.type === \"set\") {\n\t\t\t\t\t\tcallback(data.value ?? null);\n\t\t\t\t\t} else if (data.type === \"remove\") {\n\t\t\t\t\t\tcallback(null);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tchannel.addEventListener(\"message\", handler);\n\t\t\treturn () => {\n\t\t\t\tchannel.removeEventListener(\"message\", handler);\n\t\t\t};\n\t\t},\n\t};\n};\n\n/**\n * Cleanup the shared BroadcastChannel used for cross-tab cookie sync.\n * Call this when you're done using cookie storage (e.g., in tests or when unmounting).\n *\n * @remarks\n * In normal browser usage, you typically don't need to call this -\n * the channel will be cleaned up when the page is closed.\n * This is primarily useful for testing environments where multiple\n * test runs may accumulate channels.\n */\nexport const cleanupBroadcastChannel = (): void => {\n\tif (sharedBroadcastChannel) {\n\t\tsharedBroadcastChannel.close();\n\t\tsharedBroadcastChannel = null;\n\t}\n};\n","import { safeLocalStorage } from \"./storage\";\n\n/**\n * Storage key for the icon cache in localStorage.\n */\nconst ICON_CACHE_KEY = \"kheopskit-icons\";\n\n/**\n * Icon cache type: a map of wallet ID to icon data URI or URL.\n */\ntype IconCache = Record<string, string>;\n\n/**\n * In-memory cache to avoid repeated localStorage reads.\n */\nlet memoryCache: IconCache | null = null;\n\n/**\n * Loads the icon cache from localStorage.\n */\nconst loadCache = (): IconCache => {\n\tif (memoryCache !== null) return memoryCache;\n\n\ttry {\n\t\tconst stored = safeLocalStorage.getItem(ICON_CACHE_KEY);\n\t\tmemoryCache = stored ? (JSON.parse(stored) as IconCache) : {};\n\t} catch {\n\t\tmemoryCache = {};\n\t}\n\treturn memoryCache;\n};\n\n/**\n * Saves the icon cache to localStorage.\n */\nconst saveCache = (cache: IconCache): void => {\n\ttry {\n\t\tsafeLocalStorage.setItem(ICON_CACHE_KEY, JSON.stringify(cache));\n\t\tmemoryCache = cache;\n\t} catch {\n\t\t// localStorage may be full or unavailable\n\t}\n};\n\n/**\n * Gets a cached icon for a wallet.\n * @param walletId - The wallet ID (e.g., \"ethereum:io.talisman\")\n * @returns The cached icon data URI, or undefined if not cached\n */\nexport const getCachedIcon = (walletId: string): string | undefined => {\n\tconst cache = loadCache();\n\treturn cache[walletId] || undefined;\n};\n\n/**\n * Sets multiple cached icons at once.\n * More efficient than calling setCachedIcon multiple times.\n * @param icons - Map of wallet ID to icon\n */\nexport const setCachedIcons = (icons: Record<string, string>): void => {\n\tconst cache = loadCache();\n\tlet changed = false;\n\n\tfor (const [walletId, icon] of Object.entries(icons)) {\n\t\tif (icon && cache[walletId] !== icon) {\n\t\t\tcache[walletId] = icon;\n\t\t\tchanged = true;\n\t\t}\n\t}\n\n\tif (changed) {\n\t\tsaveCache(cache);\n\t}\n};\n","import type { BaseWalletAccount, WalletPlatform } from \"../api/types\";\n\nconst PLATFORM_ORDER: Record<WalletPlatform, number> = {\n\tpolkadot: 0,\n\tethereum: 1,\n\tsolana: 2,\n};\n\nconst byPlatform = (a1: BaseWalletAccount, a2: BaseWalletAccount) =>\n\tPLATFORM_ORDER[a1.platform] - PLATFORM_ORDER[a2.platform];\n\n// Group accounts by wallet, surfacing Talisman first (case-insensitive).\nconst byWalletName = (a1: BaseWalletAccount, a2: BaseWalletAccount) => {\n\tif (a1.walletName === a2.walletName) return 0;\n\tif (a1.walletName.toLowerCase() === \"talisman\") return -1;\n\tif (a2.walletName.toLowerCase() === \"talisman\") return 1;\n\treturn a1.walletName.localeCompare(a2.walletName);\n};\n\nexport const sortAccounts = (a1: BaseWalletAccount, a2: BaseWalletAccount) =>\n\tbyPlatform(a1, a2) || byWalletName(a1, a2);\n","import {\n\ttype BaseWallet,\n\tisWalletConnectWallet,\n\ttype WalletConnectWallet,\n\ttype WalletPlatform,\n} from \"../api/types\";\n\nconst PLATFORM_ORDER: Record<WalletPlatform, number> = {\n\tpolkadot: 0,\n\tethereum: 1,\n\tsolana: 2,\n};\n\n// The platform-less WalletConnect connector sorts after all platform wallets.\nconst orderOf = (wallet: BaseWallet | WalletConnectWallet) =>\n\tisWalletConnectWallet(wallet) ? 3 : PLATFORM_ORDER[wallet.platform];\n\nexport const sortWallets = (\n\tw1: BaseWallet | WalletConnectWallet,\n\tw2: BaseWallet | WalletConnectWallet,\n) => {\n\t// Sort by platform first: polkadot, then ethereum, then solana, then WC\n\tconst o1 = orderOf(w1);\n\tconst o2 = orderOf(w2);\n\tif (o1 !== o2) return o1 - o2;\n\n\t// Sort by name, but Talisman first\n\tif (w1.name.toLowerCase() === \"talisman\") return -1;\n\tif (w2.name.toLowerCase() === \"talisman\") return 1;\n\n\treturn w1.name.localeCompare(w2.name);\n};\n","import type {\n\tCachedAccount,\n\tCachedWallet,\n\tKheopskitConfig,\n\tKheopskitPlatform,\n} from \"./types\";\n\nexport const acceptsCachedWallet = (\n\tcached: CachedWallet,\n\tconfig: Pick<KheopskitConfig, \"platforms\" | \"walletConnect\">,\n): boolean =>\n\tcached.type === \"walletconnect\"\n\t\t? config.walletConnect !== undefined\n\t\t: config.platforms.some((p) => p.platform === cached.platform);\n\nexport const acceptsCachedAccount = (\n\tcached: CachedAccount,\n\tplatforms: readonly KheopskitPlatform[],\n): boolean => {\n\tconst plugin = platforms.find((p) => p.platform === cached.platform);\n\treturn (\n\t\tplugin !== undefined && (plugin.acceptsCachedAccount?.(cached) ?? true)\n\t);\n};\n","import { isEqual } from \"lodash-es\";\nimport {\n\tdistinctUntilChanged,\n\tmap,\n\ttype Observable,\n\tscan,\n\tswitchMap,\n\ttake,\n} from \"rxjs\";\nimport type { WalletId } from \"../utils/WalletId\";\nimport type { KheopskitStore } from \"./store\";\nimport type { BaseWallet, KheopskitConfig } from \"./types\";\n\n// `maxAttempts` caps retries: wallets$ re-emits on every discovery change, so a\n// connect that always rejects would otherwise be re-attempted on each one.\nexport type ReconnectPolicyOptions = {\n\t/** @default 3 */\n\tmaxAttempts?: number;\n};\n\ntype ReconnectAttemptState =\n\t| { kind: \"pending\" }\n\t| { kind: \"reconnected\" }\n\t| { kind: \"settled\" }\n\t| { kind: \"failed\"; attempts: number };\n\nexport const createReconnectPolicy = ({\n\tmaxAttempts = 3,\n}: ReconnectPolicyOptions = {}) => {\n\tconst states = new Map<string, ReconnectAttemptState>();\n\n\tconst shouldAttempt = (walletId: string): boolean => {\n\t\tconst state = states.get(walletId);\n\t\tif (!state) return true;\n\t\treturn state.kind === \"failed\" && state.attempts < maxAttempts;\n\t};\n\n\tconst attempt = async (\n\t\twalletId: string,\n\t\tconnect: () => Promise<unknown>,\n\t): Promise<boolean> => {\n\t\tif (!shouldAttempt(walletId)) return false;\n\n\t\tconst before = states.get(walletId);\n\t\tstates.set(walletId, { kind: \"pending\" });\n\t\tconst recordOutcome = (outcome: ReconnectAttemptState) => {\n\t\t\tif (states.get(walletId)?.kind !== \"settled\")\n\t\t\t\tstates.set(walletId, outcome);\n\t\t};\n\t\ttry {\n\t\t\tawait connect();\n\t\t\trecordOutcome({ kind: \"reconnected\" });\n\t\t\treturn true;\n\t\t} catch (err) {\n\t\t\tconst attempts = before?.kind === \"failed\" ? before.attempts + 1 : 1;\n\t\t\trecordOutcome({ kind: \"failed\", attempts });\n\t\t\tthrow err;\n\t\t}\n\t};\n\n\tconst settle = (walletId: string) => {\n\t\tstates.set(walletId, { kind: \"settled\" });\n\t};\n\n\treturn { shouldAttempt, attempt, settle };\n};\n\n// Shared by the first-frame snapshot and the live attempt: both must evaluate\n// `autoReconnect` identically or the server and client markup diverge.\nexport const reconnectAccepts = (\n\tautoReconnect: KheopskitConfig[\"autoReconnect\"],\n\twallet: BaseWallet,\n): boolean =>\n\ttypeof autoReconnect === \"function\" ? autoReconnect(wallet) : autoReconnect;\n\n// Wallets remembered at subscribe and never forgotten since: a connect during\n// the session never adds a reconnect, and a forget cancels one for good.\nexport const reconnectCandidates$ = (\n\tstore: KheopskitStore,\n): Observable<WalletId[]> => {\n\tconst remembered$ = store.observable.pipe(map((s) => s.remembered ?? []));\n\treturn remembered$.pipe(\n\t\ttake(1),\n\t\tswitchMap((initial) =>\n\t\t\tremembered$.pipe(\n\t\t\t\tscan(\n\t\t\t\t\t(remaining, current) =>\n\t\t\t\t\t\tremaining.filter((id) => current.includes(id)),\n\t\t\t\t\tinitial,\n\t\t\t\t),\n\t\t\t),\n\t\t),\n\t\tdistinctUntilChanged<WalletId[]>(isEqual),\n\t);\n};\n","import { hydrateAccount, hydrateWallet } from \"../utils/hydrateState\";\nimport { getCachedIcon } from \"../utils/iconCache\";\nimport { sortAccounts } from \"../utils/sortAccounts\";\nimport { sortWallets } from \"../utils/sortWallets\";\nimport { acceptsCachedAccount, acceptsCachedWallet } from \"./platform\";\nimport { reconnectAccepts } from \"./reconnectPolicy\";\nimport type { KheopskitStore } from \"./store\";\nimport type {\n\tBaseWallet,\n\tBaseWalletAccount,\n\tKheopskitConfig,\n\tWalletConnectWallet,\n} from \"./types\";\nimport { isInjectedWallet } from \"./types\";\n\n/** Result of {@link getHydratedSnapshot}: placeholder wallets and accounts built from the cache. */\nexport type HydratedSnapshot = {\n\twallets: (BaseWallet | WalletConnectWallet)[];\n\taccounts: BaseWalletAccount[];\n};\n\nexport type GetHydratedSnapshotOptions = {\n\t/**\n\t * Enrich wallets that have no icon from the localStorage icon cache.\n\t *\n\t * Must stay `false` for any snapshot that has to match server-rendered markup\n\t * (React's `getServerSnapshot` runs on the client during hydration, where the\n\t * icon cache is populated — enriching there would diverge from the server,\n\t * which always sees an empty cache).\n\t */\n\ticons?: boolean;\n};\n\n/**\n * Builds placeholder wallets and accounts from the store's cached state,\n * sorted like the live pipeline. Omits wallets of platforms missing from\n * `config.platforms`, the WalletConnect row when `config.walletConnect` is\n * unset, and every account of a platform missing from `config.platforms` or\n * whose wallet is not among the returned wallets. A cached connected injected\n * wallet that `autoReconnect` rejects comes back `disconnected`, and a wallet\n * that comes back `disconnected` has no accounts. Each remaining account must\n * pass its platform plugin's `acceptsCachedAccount` hook.\n *\n * This is the single implementation behind the observable's initial seed and\n * both React snapshot sources (`serverValue`/`initialValue`). They must produce\n * the same shape in the same order or the UI flickers/reorders on reload — by\n * sharing this helper, that agreement holds by construction.\n */\nexport const getHydratedSnapshot = (\n\tstore: KheopskitStore,\n\tconfig: Pick<\n\t\tKheopskitConfig,\n\t\t\"platforms\" | \"autoReconnect\" | \"walletConnect\"\n\t>,\n\toptions: GetHydratedSnapshotOptions = {},\n): HydratedSnapshot => {\n\tconst cached = store.getCachedState();\n\n\tconst wallets = cached.wallets\n\t\t.filter((wallet) => acceptsCachedWallet(wallet, config))\n\t\t.map(hydrateWallet)\n\t\t.map((wallet) =>\n\t\t\twallet.status === \"connecting\" &&\n\t\t\tisInjectedWallet(wallet) &&\n\t\t\t!reconnectAccepts(config.autoReconnect, wallet)\n\t\t\t\t? { ...wallet, status: \"disconnected\" as const }\n\t\t\t\t: wallet,\n\t\t)\n\t\t.map((wallet) => {\n\t\t\t// Some wallets (e.g. Ethereum) have no SSR-safe icon; optionally fill it\n\t\t\t// from the localStorage cache.\n\t\t\tif (!options.icons || wallet.icon) return wallet;\n\t\t\tconst icon = getCachedIcon(wallet.id);\n\t\t\treturn icon ? { ...wallet, icon } : wallet;\n\t\t})\n\t\t.sort(sortWallets);\n\n\tconst walletsWithAccounts = new Set(\n\t\twallets.filter((w) => w.status !== \"disconnected\").map((w) => w.id),\n\t);\n\n\tconst accounts = cached.accounts\n\t\t.filter((account) => walletsWithAccounts.has(account.walletId))\n\t\t.filter((account) => acceptsCachedAccount(account, config.platforms))\n\t\t.map(hydrateAccount)\n\t\t.sort(sortAccounts);\n\n\treturn { wallets, accounts };\n};\n","import {\n\tBehaviorSubject,\n\tcombineLatest,\n\tfilter,\n\tmap,\n\tObservable,\n\tSubscription,\n\tstartWith,\n\ttake,\n\ttimer,\n} from \"rxjs\";\n\ntype HydrationBufferResult<T> = {\n\titems: T[];\n\tisHydrating: boolean;\n};\n\nconst createBufferCore = <L, C>(\n\tcachedItems: C[],\n\tliveItems$: Observable<L[]>,\n\tgracePeriodMs: number,\n\ttimeoutMs: number,\n\tmergeFn: (liveItems: L[], cachedItems: C[]) => (L | C)[],\n\tsettled$?: Observable<boolean>,\n): Observable<HydrationBufferResult<L | C>> => {\n\tif (gracePeriodMs <= 0 || cachedItems.length === 0) {\n\t\treturn liveItems$.pipe(map((items) => ({ items, isHydrating: false })));\n\t}\n\n\treturn new Observable<HydrationBufferResult<L | C>>((subscriber) => {\n\t\tconst subscriptions = new Subscription();\n\t\tconst isHydrating$ = new BehaviorSubject(true);\n\t\tconst endHydration = () => {\n\t\t\tif (isHydrating$.value) isHydrating$.next(false);\n\t\t};\n\n\t\tconst graceElapsed$ = timer(gracePeriodMs).pipe(\n\t\t\tmap(() => true),\n\t\t\tstartWith(false),\n\t\t);\n\t\tconst ended$: Observable<unknown> = settled$\n\t\t\t? combineLatest([graceElapsed$, settled$]).pipe(\n\t\t\t\t\tfilter(([graceElapsed, settled]) => graceElapsed && settled),\n\t\t\t\t\ttake(1),\n\t\t\t\t)\n\t\t\t: timer(gracePeriodMs);\n\t\tsubscriptions.add(ended$.subscribe(endHydration));\n\t\tsubscriptions.add(timer(timeoutMs).subscribe(endHydration));\n\n\t\tsubscriptions.add(\n\t\t\tcombineLatest([liveItems$.pipe(startWith([] as L[])), isHydrating$])\n\t\t\t\t.pipe(\n\t\t\t\t\tmap(([liveItems, isHydrating]) =>\n\t\t\t\t\t\tisHydrating\n\t\t\t\t\t\t\t? { items: mergeFn(liveItems, cachedItems), isHydrating }\n\t\t\t\t\t\t\t: { items: liveItems, isHydrating },\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t\t.subscribe(subscriber),\n\t\t);\n\n\t\treturn () => {\n\t\t\tsubscriptions.unsubscribe();\n\t\t\tisHydrating$.complete();\n\t\t};\n\t});\n};\n\n/**\n * Creates a hydration buffer that merges cached items with live items.\n *\n * During hydration, cached items take precedence over live items with the same key.\n * This preserves the cached connected state (e.g., isConnected: true) while\n * auto-reconnect is still in progress. New live items not in the cache are added.\n *\n * @param cachedItems - Initial cached items from storage\n * @param liveItems$ - Observable of live items as they become available\n * @param gracePeriodMs - Minimum time in ms the cached items are shown\n * @param timeoutMs - Upper bound in ms on hydration\n * @param getKey - Function to extract a unique key from an item\n * @param settled$ - Whether the live state has caught up with the cache\n * @param mergeItem - Optional function to merge a live item with its cached counterpart\n * @param transformCachedOnly - Optional function to transform cached items not yet in the live stream\n */\nexport const createHydrationBuffer = <L, C>(\n\tcachedItems: C[],\n\tliveItems$: Observable<L[]>,\n\tgracePeriodMs: number,\n\ttimeoutMs: number,\n\tgetKey: (item: L | C) => string,\n\tsettled$?: Observable<boolean>,\n\tmergeItem?: (liveItem: L, cachedItem: C) => L | C,\n\ttransformCachedOnly?: (cachedItem: C) => C,\n): Observable<HydrationBufferResult<L | C>> => {\n\treturn createBufferCore(\n\t\tcachedItems,\n\t\tliveItems$,\n\t\tgracePeriodMs,\n\t\ttimeoutMs,\n\t\t(liveItems, cached) => {\n\t\t\tconst cachedByKey = new Map(cached.map((item) => [getKey(item), item]));\n\t\t\tconst liveKeys = new Set(liveItems.map(getKey));\n\n\t\t\t// For items in both live and cached, prefer cached (preserves connected state)\n\t\t\t// but allow mergeItem to customize how they're combined\n\t\t\t// For items only in live (newly discovered), use the live version\n\t\t\tconst mergedItems: (L | C)[] = liveItems.map((liveItem) => {\n\t\t\t\tconst key = getKey(liveItem);\n\t\t\t\tconst cachedItem = cachedByKey.get(key);\n\t\t\t\tif (!cachedItem) return liveItem;\n\t\t\t\treturn mergeItem ? mergeItem(liveItem, cachedItem) : cachedItem;\n\t\t\t});\n\n\t\t\t// Add cached items not yet in the live stream (e.g., extensions not yet detected)\n\t\t\tfor (const cachedItem of cached) {\n\t\t\t\tif (!liveKeys.has(getKey(cachedItem))) {\n\t\t\t\t\tconst transformed = transformCachedOnly\n\t\t\t\t\t\t? transformCachedOnly(cachedItem)\n\t\t\t\t\t\t: cachedItem;\n\t\t\t\t\tmergedItems.push(transformed);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn mergedItems;\n\t\t},\n\t\tsettled$,\n\t);\n};\n\n/**\n * Creates a hydration buffer specifically for accounts, which need special handling.\n *\n * Accounts are grouped by wallet - when a wallet provides its account list,\n * we replace all cached accounts for that wallet with the live ones.\n * Cached accounts for wallets that haven't provided accounts yet are preserved.\n *\n * @param cachedAccounts - Initial cached accounts from storage\n * @param liveAccounts$ - Observable of live accounts as they become available\n * @param gracePeriodMs - Minimum time in ms the cached accounts are shown\n * @param timeoutMs - Upper bound in ms on hydration\n * @param getWalletId - Function to extract the wallet ID from an account\n * @param settled$ - Whether the live state has caught up with the cache\n */\nexport const createAccountHydrationBuffer = <T>(\n\tcachedAccounts: T[],\n\tliveAccounts$: Observable<T[]>,\n\tgracePeriodMs: number,\n\ttimeoutMs: number,\n\tgetWalletId: (account: T) => string,\n\tsettled$?: Observable<boolean>,\n): Observable<HydrationBufferResult<T>> => {\n\treturn createBufferCore(\n\t\tcachedAccounts,\n\t\tliveAccounts$,\n\t\tgracePeriodMs,\n\t\ttimeoutMs,\n\t\t(liveAccounts, cached) => {\n\t\t\tconst walletsWithLiveAccounts = new Set(liveAccounts.map(getWalletId));\n\t\t\tconst mergedAccounts: T[] = [...liveAccounts];\n\n\t\t\tfor (const cachedAccount of cached) {\n\t\t\t\tif (!walletsWithLiveAccounts.has(getWalletId(cachedAccount))) {\n\t\t\t\t\tmergedAccounts.push(cachedAccount);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn mergedAccounts;\n\t\t},\n\t\tsettled$,\n\t);\n};\n","import { type MonoTypeOperatorFunction, tap } from \"rxjs\";\n\ntype Opts = {\n\tprintValue?: boolean;\n\tenabled?: boolean;\n};\n\nexport const logObservable = <T>(\n\tlabel: string,\n\topts?: Opts,\n): MonoTypeOperatorFunction<T> =>\n\ttap((value) => {\n\t\tconst { printValue = false, enabled = true } = opts || {};\n\n\t\tif (!label || !enabled) return;\n\n\t\tconst text = `[kheopskit] observable ${label} emit`;\n\n\t\tif (printValue) console.debug(text, value);\n\t\telse console.debug(text);\n\t});\n","import { combineLatest, map, Observable, of, shareReplay } from \"rxjs\";\nimport { sortAccounts } from \"../utils/sortAccounts\";\nimport { framesOf, type PlatformAccountsFrame } from \"./platformAccounts\";\nimport type {\n\tBaseWallet,\n\tBaseWalletAccount,\n\tKheopskitConfig,\n\tWalletConnectWallet,\n} from \"./types\";\nimport { isWalletConnectWallet } from \"./types\";\n\nexport type AccountsFrame = PlatformAccountsFrame<BaseWalletAccount>;\n\nexport const getAccounts$ = (\n\tconfig: KheopskitConfig,\n\twallets: Observable<(BaseWallet | WalletConnectWallet)[]>,\n) => {\n\treturn new Observable<AccountsFrame>((subscriber) => {\n\t\t// Each plugin gets its own platform's (injected) wallets plus the shared\n\t\t// WalletConnect connector; it derives WC accounts only for the namespaces\n\t\t// the session carries.\n\t\tconst sources = config.platforms.map((plugin) =>\n\t\t\tframesOf(\n\t\t\t\tplugin.getAccounts$(\n\t\t\t\t\twallets.pipe(\n\t\t\t\t\t\tmap((ws) =>\n\t\t\t\t\t\t\tws.filter(\n\t\t\t\t\t\t\t\t(w) =>\n\t\t\t\t\t\t\t\t\tisWalletConnectWallet(w) || w.platform === plugin.platform,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t),\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t),\n\t\t);\n\n\t\tconst frames$ = sources.length\n\t\t\t? combineLatest(sources).pipe(\n\t\t\t\t\tmap((frames) => ({\n\t\t\t\t\t\taccounts: frames\n\t\t\t\t\t\t\t.flatMap((frame) => frame.accounts)\n\t\t\t\t\t\t\t.sort(sortAccounts),\n\t\t\t\t\t\tanswered: frames.flatMap((frame) => frame.answered),\n\t\t\t\t\t})),\n\t\t\t\t)\n\t\t\t: of<AccountsFrame>({ accounts: [], answered: [] });\n\n\t\tconst sub = frames$.subscribe(subscriber);\n\n\t\treturn () => {\n\t\t\tsub.unsubscribe();\n\t\t};\n\t}).pipe(shareReplay({ refCount: true, bufferSize: 1 }));\n};\n","import { BehaviorSubject, Observable } from \"rxjs\";\nimport { type SyncableStorage, safeLocalStorage } from \"./storage\";\n\nexport const createStore = <T>(\n\tkey: string,\n\tdefaultValue: T,\n\tstorage: SyncableStorage = safeLocalStorage,\n\tnormalize: (value: T) => T = (value) => value,\n) => {\n\tconst read = (str: string | null) => normalize(parseData(str, defaultValue));\n\tconst syncsAcrossTabs =\n\t\ttypeof window !== \"undefined\" && storage.subscribe !== undefined;\n\tconst subject = new BehaviorSubject<T>(read(storage.getItem(key)));\n\tlet observers = 0;\n\tlet stopSync: (() => void) | undefined;\n\n\tconst latestValue = () => {\n\t\tif (syncsAcrossTabs && observers === 0)\n\t\t\tsubject.next(read(storage.getItem(key)));\n\t\treturn subject.getValue();\n\t};\n\n\tconst observable = new Observable<T>((subscriber) => {\n\t\tif (observers === 0 && syncsAcrossTabs) {\n\t\t\tlatestValue();\n\t\t\tstopSync = storage.subscribe?.(key, (newValue) => {\n\t\t\t\tsubject.next(read(newValue));\n\t\t\t});\n\t\t}\n\t\tobservers++;\n\t\tconst subscription = subject.subscribe(subscriber);\n\t\treturn () => {\n\t\t\tsubscription.unsubscribe();\n\t\t\tobservers--;\n\t\t\tif (observers === 0) stopSync?.();\n\t\t};\n\t});\n\n\tconst update = (val: T) => {\n\t\tpersistBestEffort(key, val, storage);\n\t\tsubject.next(val);\n\t};\n\n\treturn {\n\t\tobservable,\n\t\tset: (val: T) => update(val),\n\t\tmutate: (transform: (prev: T) => T) => update(transform(latestValue())),\n\t\tget: () => structuredClone(latestValue()),\n\t\tdestroy: () => subject.complete(),\n\t};\n};\n\nconst parseData = <T>(str: string | null, defaultValue: T): T => {\n\ttry {\n\t\tif (str) return JSON.parse(str);\n\t} catch {\n\t\t// invalid data\n\t}\n\treturn defaultValue;\n};\n\nconst persistBestEffort = <T>(\n\tkey: string,\n\tval: T,\n\tstorage: SyncableStorage,\n) => {\n\tconst str = JSON.stringify(val);\n\ttry {\n\t\tstorage.setItem(key, str);\n\t} catch {}\n};\n","import { isWalletPlatform } from \"../utils/isWalletPlatform\";\nimport { cookieStorage } from \"../utils/storage\";\nimport { getWalletAccountId } from \"../utils/WalletAccountId\";\nimport {\n\tisValidWalletId,\n\tparseWalletId,\n\tWALLET_CONNECT_WALLET_ID,\n\ttype WalletId,\n} from \"../utils/WalletId\";\nimport type {\n\tCachedAccount,\n\tCachedWallet,\n\tKheopskitStoreData,\n\tWalletPlatform,\n} from \"./types\";\n\n/**\n * Compact wire format for the cookie-persisted store (`CompactStoreV1`).\n *\n * Cookies are size-constrained (~4KB per cookie, sent on every request), so the\n * persisted {@link KheopskitStoreData} is encoded as terse tuples with\n * single-letter keys instead of raw JSON. This module owns that format: the\n * encoder, the defensive decoder, and the lazy migration from the legacy\n * verbose-JSON cookies written by older versions.\n *\n * Any change here is a compatibility question — new fields must be optional and\n * decoding must keep accepting everything older versions wrote (or degrade to\n * \"start fresh\", never throw).\n */\n\n// wallet type: 0=injected, 1=walletconnect\ntype CompactWalletEntry = [WalletId, string, 0 | 1, 0 | 1];\ntype CompactPolkadotAccountType = 0 | 1 | 2 | 3;\n// platform: 0=polkadot, 1=ethereum, 2=solana\ntype CompactPlatformCode = 0 | 1 | 2;\ntype CompactAccountEntry = [\n\tWalletId,\n\tstring,\n\tstring | null,\n\tnumber | null,\n\tCompactPolkadotAccountType | null,\n\t// Platform code. Newly written entries always include it (the WalletConnect\n\t// connector's walletId is platform-less, so platform can't be derived from\n\t// it); absent in entries written by older versions, where it's derived from\n\t// the walletId instead.\n\t(CompactPlatformCode | null)?,\n];\n\ntype CompactStoreV1 = {\n\tv: 1;\n\t// remembered\n\tr?: WalletId[];\n\t// wallets: [id, name, isConnected(0|1), type(0=injected,1=walletconnect)?]\n\tw?: CompactWalletEntry[];\n\t// accounts: [walletId, address, name?, chainId?, polkadotType?, platform?]\n\ta?: CompactAccountEntry[];\n};\n\nconst EMPTY_STORE_DATA: KheopskitStoreData = {};\n\ntype PreV6StoreData = KheopskitStoreData & { autoReconnect?: unknown };\n\nexport const migratePreV6StoreData = (\n\tdata: PreV6StoreData,\n): KheopskitStoreData => {\n\tif (data?.autoReconnect === undefined) return data;\n\tconst { autoReconnect, ...rest } = data;\n\treturn rest.remembered === undefined && Array.isArray(autoReconnect)\n\t\t? { ...rest, remembered: autoReconnect }\n\t\t: rest;\n};\n\nconst toCompactPolkadotAccountType = (\n\ttype: CachedAccount[\"polkadotAccountType\"],\n): CompactPolkadotAccountType | null => {\n\tswitch (type) {\n\t\tcase \"sr25519\":\n\t\t\treturn 0;\n\t\tcase \"ed25519\":\n\t\t\treturn 1;\n\t\tcase \"ecdsa\":\n\t\t\treturn 2;\n\t\tcase \"ethereum\":\n\t\t\treturn 3;\n\t\tdefault:\n\t\t\treturn null;\n\t}\n};\n\nconst fromCompactPolkadotAccountType = (\n\ttype: CompactPolkadotAccountType | null | undefined,\n): CachedAccount[\"polkadotAccountType\"] => {\n\tswitch (type) {\n\t\tcase 0:\n\t\t\treturn \"sr25519\";\n\t\tcase 1:\n\t\t\treturn \"ed25519\";\n\t\tcase 2:\n\t\t\treturn \"ecdsa\";\n\t\tcase 3:\n\t\t\treturn \"ethereum\";\n\t\tdefault:\n\t\t\treturn undefined;\n\t}\n};\n\nconst toCompactPlatform = (platform: WalletPlatform): CompactPlatformCode => {\n\tswitch (platform) {\n\t\tcase \"polkadot\":\n\t\t\treturn 0;\n\t\tcase \"ethereum\":\n\t\t\treturn 1;\n\t\tcase \"solana\":\n\t\t\treturn 2;\n\t}\n};\n\nconst fromCompactPlatform = (\n\tcode: CompactPlatformCode | null | undefined,\n): WalletPlatform | undefined => {\n\tswitch (code) {\n\t\tcase 0:\n\t\t\treturn \"polkadot\";\n\t\tcase 1:\n\t\t\treturn \"ethereum\";\n\t\tcase 2:\n\t\t\treturn \"solana\";\n\t\tdefault:\n\t\t\treturn undefined;\n\t}\n};\n\nconst isCompactStore = (value: unknown): value is CompactStoreV1 => {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) return false;\n\tif (\"cachedWallets\" in value || \"cachedAccounts\" in value) return false;\n\treturn \"v\" in value || \"w\" in value || \"a\" in value || \"r\" in value;\n};\n\nconst toCompactStore = (data: KheopskitStoreData): CompactStoreV1 => {\n\tconst wallets = data.cachedWallets?.map(\n\t\t(wallet): CompactWalletEntry => [\n\t\t\twallet.id,\n\t\t\twallet.name,\n\t\t\twallet.isConnected ? 1 : 0,\n\t\t\twallet.type === \"walletconnect\" ? 1 : 0,\n\t\t],\n\t);\n\n\tconst accounts = data.cachedAccounts?.map(\n\t\t(account): CompactAccountEntry => [\n\t\t\taccount.walletId,\n\t\t\taccount.address,\n\t\t\taccount.name ?? null,\n\t\t\taccount.chainId ?? null,\n\t\t\ttoCompactPolkadotAccountType(account.polkadotAccountType),\n\t\t\ttoCompactPlatform(account.platform),\n\t\t],\n\t);\n\n\treturn {\n\t\tv: 1,\n\t\tr: data.remembered,\n\t\tw: wallets?.length ? wallets : undefined,\n\t\ta: accounts?.length ? accounts : undefined,\n\t};\n};\n\nconst fromCompactStore = (data: CompactStoreV1): KheopskitStoreData => {\n\tconst walletNameMap = new Map<WalletId, string>();\n\n\t// Decode defensively: a compact payload may be malformed (older/corrupt\n\t// cookie, hand-edited). Skip entries with an unparseable wallet id rather\n\t// than throwing, which would crash store initialisation.\n\tconst wallets: CachedWallet[] = [];\n\tfor (const item of Array.isArray(data.w) ? data.w : []) {\n\t\tif (!Array.isArray(item)) continue;\n\t\tconst [id, name, isConnected, type] = item;\n\t\tif (!isValidWalletId(id)) continue;\n\t\tconst isWalletConnect = id === WALLET_CONNECT_WALLET_ID;\n\t\tconst walletType = type === 1 ? \"walletconnect\" : \"injected\";\n\t\t// Keep id/type consistent: the platform-less connector uses the fixed WC\n\t\t// id; everything else is a platform-prefixed injected wallet. Drop stale\n\t\t// mismatches (e.g. per-platform WC ids from older versions).\n\t\tif (isWalletConnect !== (walletType === \"walletconnect\")) continue;\n\t\twalletNameMap.set(id, name);\n\t\twallets.push({\n\t\t\tid,\n\t\t\tplatform: isWalletConnect ? undefined : parseWalletId(id).platform,\n\t\t\ttype: walletType,\n\t\t\tname,\n\t\t\tisConnected: isConnected === 1,\n\t\t});\n\t}\n\n\tconst accounts: CachedAccount[] = [];\n\tfor (const item of Array.isArray(data.a) ? data.a : []) {\n\t\tif (!Array.isArray(item)) continue;\n\t\tconst [\n\t\t\twalletId,\n\t\t\taddress,\n\t\t\tname,\n\t\t\tchainId,\n\t\t\tpolkadotAccountType,\n\t\t\tplatformCode,\n\t\t] = item;\n\t\tif (!isValidWalletId(walletId) || typeof address !== \"string\" || !address)\n\t\t\tcontinue;\n\t\t// Prefer the explicit platform code; fall back to deriving it from the\n\t\t// walletId for entries written before the code existed (never WC ones).\n\t\tconst platform =\n\t\t\tplatformCode != null\n\t\t\t\t? fromCompactPlatform(platformCode)\n\t\t\t\t: walletId === WALLET_CONNECT_WALLET_ID\n\t\t\t\t\t? undefined\n\t\t\t\t\t: parseWalletId(walletId).platform;\n\t\tif (!isWalletPlatform(platform)) continue;\n\t\taccounts.push({\n\t\t\tid: getWalletAccountId(walletId, address),\n\t\t\tplatform,\n\t\t\taddress,\n\t\t\tname: name ?? undefined,\n\t\t\tchainId: chainId ?? undefined,\n\t\t\tpolkadotAccountType:\n\t\t\t\tplatform === \"polkadot\"\n\t\t\t\t\t? fromCompactPolkadotAccountType(polkadotAccountType)\n\t\t\t\t\t: undefined,\n\t\t\twalletId,\n\t\t\twalletName: walletNameMap.get(walletId) ?? walletId,\n\t\t});\n\t}\n\n\treturn {\n\t\tremembered: data.r,\n\t\tcachedWallets: wallets,\n\t\tcachedAccounts: accounts,\n\t};\n};\n\nconst decodeStore = (raw: string, fallback: KheopskitStoreData) => {\n\ttry {\n\t\tconst parsed = JSON.parse(raw) as unknown;\n\t\tif (isCompactStore(parsed)) return fromCompactStore(parsed);\n\t\treturn migratePreV6StoreData(parsed as PreV6StoreData);\n\t} catch {\n\t\treturn fallback;\n\t}\n};\n\nconst encodeStore = (data: KheopskitStoreData): string =>\n\tJSON.stringify(toCompactStore(data));\n\n/**\n * Cookie storage that transparently encodes/decodes {@link CompactStoreV1},\n * migrating legacy verbose-JSON cookies to the compact format on first read.\n */\nexport const createCompactCookieStorage = (initialCookies?: string) => {\n\tconst base = cookieStorage(initialCookies);\n\n\treturn {\n\t\tgetItem: (key: string) => {\n\t\t\tconst raw = base.getItem(key);\n\t\t\tif (!raw) return null;\n\t\t\tconst expanded = decodeStore(raw, EMPTY_STORE_DATA);\n\t\t\tif (typeof document !== \"undefined\") {\n\t\t\t\ttry {\n\t\t\t\t\tconst parsed = JSON.parse(raw) as unknown;\n\t\t\t\t\tif (!isCompactStore(parsed)) {\n\t\t\t\t\t\tbase.setItem(key, encodeStore(expanded));\n\t\t\t\t\t}\n\t\t\t\t} catch {\n\t\t\t\t\t// Ignore malformed cookie during migration\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn JSON.stringify(expanded);\n\t\t},\n\t\tsetItem: (key: string, value: string) => {\n\t\t\tconst expanded = decodeStore(value, EMPTY_STORE_DATA);\n\t\t\tbase.setItem(key, encodeStore(expanded));\n\t\t},\n\t\tremoveItem: base.removeItem,\n\t\tsubscribe: (key: string, callback: (value: string | null) => void) => {\n\t\t\tconst unsubscribe = base.subscribe?.(key, (value) => {\n\t\t\t\tif (!value) {\n\t\t\t\t\tcallback(null);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst expanded = decodeStore(value, EMPTY_STORE_DATA);\n\t\t\t\tcallback(JSON.stringify(expanded));\n\t\t\t});\n\t\t\treturn () => {\n\t\t\t\tunsubscribe?.();\n\t\t\t};\n\t\t},\n\t};\n};\n","import { uniq } from \"lodash-es\";\nimport { createStore } from \"../utils/createStore\";\nimport { isWalletPlatform } from \"../utils/isWalletPlatform\";\nimport { type SyncableStorage, safeLocalStorage } from \"../utils/storage\";\nimport {\n\tisValidWalletId,\n\tparseWalletId,\n\tWALLET_CONNECT_WALLET_ID,\n\ttype WalletId,\n} from \"../utils/WalletId\";\nimport {\n\tcreateCompactCookieStorage,\n\tmigratePreV6StoreData,\n} from \"./compactStore\";\nimport { DEFAULT_STORAGE_KEY } from \"./config\";\nimport type {\n\tCachedAccount,\n\tCachedWallet,\n\tKheopskitStore,\n\tKheopskitStoreData,\n} from \"./types\";\n\nexport type { KheopskitStore } from \"./types\";\n\nconst DEFAULT_SETTINGS: KheopskitStoreData = {};\n\n/**\n * Validates a cached wallet read from persisted storage. Cached state may have\n * been written by an older (or corrupted) version with a different shape, so we\n * drop anything that wouldn't survive hydration/sort rather than letting it\n * throw at render time. Only the fields downstream code relies on are checked.\n */\nconst isValidCachedWallet = (value: unknown): value is CachedWallet => {\n\tif (!value || typeof value !== \"object\") return false;\n\tconst w = value as Record<string, unknown>;\n\tif (!isValidWalletId(w.id)) return false;\n\tif (typeof w.name !== \"string\" || typeof w.isConnected !== \"boolean\")\n\t\treturn false;\n\t// The WalletConnect connector is platform-less with a fixed id; drop stale\n\t// per-platform WC entries written by older versions.\n\tif (w.type === \"walletconnect\")\n\t\treturn w.id === WALLET_CONNECT_WALLET_ID && w.platform === undefined;\n\treturn w.type === \"injected\" && isWalletPlatform(w.platform);\n};\n\n/** Validates a cached account read from persisted storage. See {@link isValidCachedWallet}. */\nconst isValidCachedAccount = (value: unknown): value is CachedAccount => {\n\tif (!value || typeof value !== \"object\") return false;\n\tconst a = value as Record<string, unknown>;\n\treturn (\n\t\ttypeof a.id === \"string\" &&\n\t\t!!a.id &&\n\t\tisWalletPlatform(a.platform) &&\n\t\ttypeof a.address === \"string\" &&\n\t\t!!a.address &&\n\t\tisValidWalletId(a.walletId) &&\n\t\ttypeof a.walletName === \"string\"\n\t);\n};\n\ntype CreateKheopskitStoreOptions = {\n\t/**\n\t * Storage backend to persist into. When provided, it takes precedence over\n\t * `ssrCookies` and localStorage.\n\t */\n\tstorage?: SyncableStorage;\n\t/**\n\t * Cookie string for SSR hydration.\n\t * When provided, uses cookieStorage instead of localStorage.\n\t */\n\tssrCookies?: string;\n\t/**\n\t * Custom storage key to namespace the stored data.\n\t * @default \"kheopskit\"\n\t */\n\tstorageKey?: string;\n};\n\n/**\n * Creates a kheopskit store with the appropriate storage backend.\n * Uses the given `storage` when provided, else cookieStorage when ssrCookies is\n * provided (for SSR hydration), otherwise safeLocalStorage.\n *\n * @param options - Configuration options for the store\n */\nexport const createKheopskitStore = (\n\toptions: CreateKheopskitStoreOptions = {},\n): KheopskitStore => {\n\tconst { ssrCookies, storageKey = DEFAULT_STORAGE_KEY } = options;\n\tconst storage =\n\t\toptions.storage ??\n\t\t(ssrCookies !== undefined\n\t\t\t? createCompactCookieStorage(ssrCookies)\n\t\t\t: safeLocalStorage);\n\tconst store = createStore(\n\t\tstorageKey,\n\t\tDEFAULT_SETTINGS,\n\t\tstorage,\n\t\tmigratePreV6StoreData,\n\t);\n\n\tconst rememberWallet = (walletId: WalletId) => {\n\t\tparseWalletId(walletId); // validate walletId\n\t\tstore.mutate((prev) => ({\n\t\t\t...prev,\n\t\t\tremembered: uniq((prev.remembered ?? []).concat(walletId)),\n\t\t}));\n\t};\n\n\tconst forgetWallet = (walletId: WalletId) => {\n\t\tstore.mutate((prev) => ({\n\t\t\t...prev,\n\t\t\tremembered: uniq((prev.remembered ?? []).filter((id) => id !== walletId)),\n\t\t}));\n\t};\n\n\tconst getCachedState = () => {\n\t\t// `store.get()` returns whatever JSON was persisted — it may be from an\n\t\t// older version, a different shape, or outright corrupt. Read defensively:\n\t\t// coerce non-objects/arrays to empty and drop any entry that fails\n\t\t// validation, so stale cache degrades to \"start fresh\" instead of throwing\n\t\t// during hydration (which renders eagerly, so a throw blanks the dapp).\n\t\tconst data = store.get() as Partial<KheopskitStoreData> | null | undefined;\n\t\tconst cachedWallets = Array.isArray(data?.cachedWallets)\n\t\t\t? data.cachedWallets\n\t\t\t: [];\n\t\tconst cachedAccounts = Array.isArray(data?.cachedAccounts)\n\t\t\t? data.cachedAccounts\n\t\t\t: [];\n\t\treturn {\n\t\t\twallets: cachedWallets.filter(isValidCachedWallet),\n\t\t\taccounts: cachedAccounts.filter(isValidCachedAccount),\n\t\t};\n\t};\n\n\tconst setCachedState = (\n\t\twallets: CachedWallet[],\n\t\taccounts: CachedAccount[],\n\t) => {\n\t\tstore.mutate((prev) => ({\n\t\t\t...prev,\n\t\t\tcachedWallets: wallets,\n\t\t\tcachedAccounts: accounts,\n\t\t}));\n\t};\n\n\treturn {\n\t\tobservable: store.observable,\n\t\trememberWallet,\n\t\tforgetWallet,\n\t\tgetCachedState,\n\t\tsetCachedState,\n\t\tdestroy: store.destroy,\n\t};\n};\n\n/**\n * Cached default store instance, anchored on globalThis so it stays a single\n * instance even if this module is duplicated across bundle chunks (e.g. CJS\n * subpath entries). Lazily initialized on first access to be SSR-safe.\n */\nconst DEFAULT_STORE_SYMBOL = Symbol.for(\"kheopskit.defaultStore\");\n\n/**\n * Gets the default store, creating it on first access.\n * Uses localStorage on client, noop on server.\n * Lazily initialized to avoid SSR issues with module-level code.\n */\nexport const getDefaultStore = (): KheopskitStore => {\n\tconst g = globalThis as unknown as Record<symbol, KheopskitStore | undefined>;\n\tif (!g[DEFAULT_STORE_SYMBOL]) {\n\t\tg[DEFAULT_STORE_SYMBOL] = createKheopskitStore();\n\t}\n\treturn g[DEFAULT_STORE_SYMBOL];\n};\n","import {\n\tcombineLatest,\n\tfilter,\n\tmap,\n\tmergeMap,\n\tObservable,\n\tof,\n\tshareReplay,\n\tstartWith,\n\ttap,\n\twithLatestFrom,\n} from \"rxjs\";\nimport { sortWallets } from \"../utils/sortWallets\";\nimport { KheopskitError } from \"./errors\";\nimport {\n\tcreateReconnectPolicy,\n\treconnectAccepts,\n\treconnectCandidates$,\n} from \"./reconnectPolicy\";\nimport type { KheopskitStore } from \"./store\";\nimport type {\n\tBaseWallet,\n\tConnectOptions,\n\tKheopskitConfig,\n\tPlatformContext,\n\tWalletConnectWallet,\n} from \"./types\";\nimport { isInjectedWallet } from \"./types\";\n\nexport const getWallets$ = (\n\tconfig: KheopskitConfig,\n\tstore: KheopskitStore,\n\tregistryReads$?: Observable<void>,\n\twalletConnect$ = config.walletConnect?.getWallet$({\n\t\tconfig,\n\t\tstore,\n\t\tregistryReads$,\n\t}),\n) => {\n\treturn new Observable<(BaseWallet | WalletConnectWallet)[]>((subscriber) => {\n\t\tconst ctx: PlatformContext = { config, store, registryReads$ };\n\t\tconst observables = config.platforms.map((plugin) =>\n\t\t\tplugin.getWallets$(ctx),\n\t\t);\n\n\t\tconst reconnectPolicy = createReconnectPolicy();\n\n\t\tconst settleOnUserCall = <W extends BaseWallet>(wallet: W): W => ({\n\t\t\t...wallet,\n\t\t\tconnect: (options?: ConnectOptions) => {\n\t\t\t\treconnectPolicy.settle(wallet.id);\n\t\t\t\treturn wallet.connect(options);\n\t\t\t},\n\t\t\tdisconnect: () => {\n\t\t\t\treconnectPolicy.settle(wallet.id);\n\t\t\t\treturn wallet.disconnect();\n\t\t\t},\n\t\t});\n\n\t\tconst platformWallets$ = observables.length\n\t\t\t? combineLatest(observables).pipe(map((wallets) => wallets.flat()))\n\t\t\t: of<BaseWallet[]>([]);\n\n\t\t// The single, platform-less WalletConnect connector is appended here (not\n\t\t// emitted per platform). It sorts last (see sortWallets). Platform wallets\n\t\t// are listed without waiting for AppKit to load.\n\t\tconst unsortedWallets$: Observable<(BaseWallet | WalletConnectWallet)[]> =\n\t\t\twalletConnect$\n\t\t\t\t? combineLatest([\n\t\t\t\t\t\tplatformWallets$,\n\t\t\t\t\t\twalletConnect$.pipe(startWith(null)),\n\t\t\t\t\t]).pipe(\n\t\t\t\t\t\tmap(([platformWallets, walletConnect]) =>\n\t\t\t\t\t\t\twalletConnect\n\t\t\t\t\t\t\t\t? [...platformWallets, walletConnect]\n\t\t\t\t\t\t\t\t: platformWallets,\n\t\t\t\t\t\t),\n\t\t\t\t\t)\n\t\t\t\t: platformWallets$;\n\t\tconst rawWallets$ = unsortedWallets$.pipe(\n\t\t\tmap((all) => all.sort(sortWallets)),\n\t\t);\n\n\t\tconst wallets$ = rawWallets$.pipe(\n\t\t\tmap((wallets) =>\n\t\t\t\twallets.map((wallet) =>\n\t\t\t\t\tisInjectedWallet(wallet) ? settleOnUserCall(wallet) : wallet,\n\t\t\t\t),\n\t\t\t),\n\t\t);\n\n\t\tconst reconnect = async (wallet: BaseWallet) => {\n\t\t\ttry {\n\t\t\t\tawait reconnectPolicy.attempt(wallet.id, () => wallet.connect());\n\t\t\t} catch (err) {\n\t\t\t\tif (subscriber.closed) return;\n\t\t\t\tif (err instanceof KheopskitError) {\n\t\t\t\t\tif (err.code === \"USER_REJECTED\") store.forgetWallet(wallet.id);\n\t\t\t\t\tif (err.code === \"USER_REJECTED\" || err.code === \"ABORTED\")\n\t\t\t\t\t\treconnectPolicy.settle(wallet.id);\n\t\t\t\t}\n\t\t\t\tif (config.debug)\n\t\t\t\t\tconsole.debug(\"[kheopskit] reconnect of %s failed\", wallet.id, err);\n\t\t\t}\n\t\t};\n\n\t\tconst subWallets = wallets$.subscribe(subscriber);\n\t\tif (subscriber.closed) return subWallets;\n\n\t\tconst subAutoReconnect = rawWallets$\n\t\t\t.pipe(\n\t\t\t\twithLatestFrom(reconnectCandidates$(store)),\n\t\t\t\tfilter(\n\t\t\t\t\t([, walletIds]) =>\n\t\t\t\t\t\tconfig.autoReconnect !== false && walletIds.length > 0,\n\t\t\t\t),\n\t\t\t\tmergeMap(([wallets, walletIds]) =>\n\t\t\t\t\twallets\n\t\t\t\t\t\t.filter(isInjectedWallet)\n\t\t\t\t\t\t.filter((wallet) => walletIds.includes(wallet.id)),\n\t\t\t\t),\n\t\t\t\ttap((wallet) => {\n\t\t\t\t\tif (wallet.status === \"connected\") reconnectPolicy.settle(wallet.id);\n\t\t\t\t}),\n\t\t\t\tfilter(\n\t\t\t\t\t(wallet) =>\n\t\t\t\t\t\twallet.status === \"disconnected\" &&\n\t\t\t\t\t\treconnectAccepts(config.autoReconnect, wallet),\n\t\t\t\t),\n\t\t\t)\n\t\t\t.subscribe(reconnect);\n\n\t\treturn () => {\n\t\t\tsubAutoReconnect.unsubscribe();\n\t\t\tsubWallets.unsubscribe();\n\t\t};\n\t}).pipe(shareReplay({ refCount: true, bufferSize: 1 }));\n};\n","import {\n\tasapScheduler,\n\tcombineLatest,\n\tconcat,\n\tdebounceTime,\n\tdistinctUntilChanged,\n\tEMPTY,\n\tfilter,\n\tignoreElements,\n\tmap,\n\tObservable,\n\tof,\n\tshareReplay,\n\tstartWith,\n\ttake,\n\ttap,\n} from \"rxjs\";\nimport {\n\tcreateAccountHydrationBuffer,\n\tcreateHydrationBuffer,\n} from \"../utils/createHydrationBuffer\";\nimport { serializeAccount, serializeWallet } from \"../utils/hydrateState\";\nimport { getCachedIcon, setCachedIcons } from \"../utils/iconCache\";\nimport { logObservable } from \"../utils/logObservable\";\nimport { createRegistryReads$ } from \"../utils/registryReads\";\nimport { sortAccounts } from \"../utils/sortAccounts\";\nimport { sortWallets } from \"../utils/sortWallets\";\nimport type { WalletId } from \"../utils/WalletId\";\nimport { type AccountsFrame, getAccounts$ } from \"./accounts\";\nimport { resolveConfig } from \"./config\";\nimport { abortedError, walletPendingError } from \"./errors\";\nimport { getHydratedSnapshot } from \"./hydration\";\nimport { reconnectCandidates$ } from \"./reconnectPolicy\";\nimport { createKheopskitStore } from \"./store\";\nimport type {\n\tBaseWallet,\n\tBaseWalletAccount,\n\tCachedAccount,\n\tCachedWallet,\n\tKheopskitConfig,\n\tKheopskitPlatform,\n\tKheopskitState,\n\tWalletConnectWallet,\n} from \"./types\";\nimport { isInjectedWallet, isWalletConnectWallet } from \"./types\";\nimport { getWallets$ } from \"./wallets\";\n\nexport type { KheopskitConfig, KheopskitState } from \"./types\";\n\nexport type KheopskitRunOptions = {\n\t/**\n\t * Cookie string for SSR hydration. When provided, state is read from cookies\n\t * instead of localStorage so the server can hydrate without a flash. Pass the\n\t * request's `cookie` header.\n\t */\n\tssrCookies?: string;\n\t/**\n\t * An existing store to reuse instead of creating one.\n\t */\n\tstore?: ReturnType<typeof createKheopskitStore>;\n};\n\nexport const kheopskitRun$ = <\n\tconst P extends readonly KheopskitPlatform[] = readonly KheopskitPlatform[],\n>(\n\tconfig?: Partial<KheopskitConfig<P>>,\n\toptions: KheopskitRunOptions = {},\n): Observable<KheopskitState<P>> => {\n\tconst { ssrCookies, store: existingStore } = options;\n\tconst kc = resolveConfig(config);\n\tconst store =\n\t\texistingStore ??\n\t\tcreateKheopskitStore({ ssrCookies, storageKey: kc.storageKey });\n\n\tif (kc.debug) console.debug(\"[kheopskit] config\", kc);\n\n\t// Warn about SSR environment without cookies\n\tif (kc.debug && typeof window === \"undefined\" && ssrCookies === undefined) {\n\t\tconsole.warn(\n\t\t\t\"[kheopskit] Running on server without `ssrCookies`. \" +\n\t\t\t\t\"Wallet state will not be hydrated. Pass cookies for SSR support.\",\n\t\t);\n\t}\n\n\t// Get cached state for hydration (same snapshot the React provider builds)\n\tconst { wallets: cachedWallets, accounts: cachedAccounts } =\n\t\tgetHydratedSnapshot(store, kc, { icons: true });\n\n\tif (kc.debug && cachedWallets.length > 0) {\n\t\tconsole.debug(\"[kheopskit] hydrating from cache:\", {\n\t\t\twallets: cachedWallets.length,\n\t\t\taccounts: cachedAccounts.length,\n\t\t});\n\t}\n\n\treturn new Observable<KheopskitState>((subscriber) => {\n\t\tlet latest: KheopskitState | undefined;\n\t\tlet closed = false;\n\t\tconst waiters = new Set<StateWaiter>();\n\t\tconst liveWaiters = new Set<(state: KheopskitState | undefined) => void>();\n\t\tconst wrapped = new WeakMap<\n\t\t\tBaseWallet | WalletConnectWallet,\n\t\t\tBaseWallet | WalletConnectWallet\n\t\t>();\n\n\t\tconst abandon = (waiter: StateWaiter) => {\n\t\t\twaiters.delete(waiter);\n\t\t\tif (waiter.isConnected)\n\t\t\t\twaiter.reject(abortedError(waiter.walletId, \"connect\"));\n\t\t\telse waiter.resolve();\n\t\t};\n\n\t\tconst settleIn = (waiter: StateWaiter, state: KheopskitState) => {\n\t\t\tconst wallet = state.wallets.find((w) => w.id === waiter.walletId);\n\t\t\tif (!wallet || wallet.isConnected === waiter.isConnected) {\n\t\t\t\twaiters.delete(waiter);\n\t\t\t\twaiter.resolve();\n\t\t\t}\n\t\t};\n\n\t\tconst supersede = (walletId: WalletId, isConnected: boolean) => {\n\t\t\tfor (const waiter of waiters)\n\t\t\t\tif (waiter.walletId === walletId && waiter.isConnected !== isConnected)\n\t\t\t\t\tabandon(waiter);\n\t\t};\n\n\t\tconst whenState = (walletId: WalletId, isConnected: boolean) =>\n\t\t\tnew Promise<void>((resolve, reject) => {\n\t\t\t\tconst waiter = { walletId, isConnected, resolve, reject };\n\t\t\t\twaiters.add(waiter);\n\t\t\t\tif (latest) settleIn(waiter, latest);\n\t\t\t\tif (closed && waiters.has(waiter)) abandon(waiter);\n\t\t\t});\n\n\t\tconst whenLive = (walletId: WalletId, signal: AbortSignal | undefined) =>\n\t\t\tnew Promise<BaseWallet | WalletConnectWallet>((resolve, reject) => {\n\t\t\t\tconst settle = (finish: () => void) => {\n\t\t\t\t\tliveWaiters.delete(check);\n\t\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\t\tfinish();\n\t\t\t\t};\n\t\t\t\tconst onAbort = () =>\n\t\t\t\t\tsettle(() => reject(abortedError(walletId, \"connect\")));\n\t\t\t\tconst check = (state: KheopskitState | undefined) => {\n\t\t\t\t\tif (!state) return onAbort();\n\t\t\t\t\tconst live = state.wallets.find(\n\t\t\t\t\t\t(w) => w.id === walletId && !w.isPlaceholder,\n\t\t\t\t\t);\n\t\t\t\t\tif (live) settle(() => resolve(live));\n\t\t\t\t\telse if (!state.isHydrating)\n\t\t\t\t\t\tsettle(() => reject(walletPendingError(walletId)));\n\t\t\t\t};\n\t\t\t\tif (closed || signal?.aborted) return onAbort();\n\t\t\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\t\tliveWaiters.add(check);\n\t\t\t\tif (latest) check(latest);\n\t\t\t});\n\n\t\tconst deferToLive = (\n\t\t\tplaceholder: BaseWallet | WalletConnectWallet,\n\t\t): BaseWallet | WalletConnectWallet => ({\n\t\t\t...placeholder,\n\t\t\tconnect: async (options) => {\n\t\t\t\tconst live = await whenLive(placeholder.id, options?.signal);\n\t\t\t\tif (closed) throw abortedError(placeholder.id, \"connect\");\n\t\t\t\tawait live.connect(options);\n\t\t\t},\n\t\t\tdisconnect: async () => {\n\t\t\t\tif (closed) return;\n\t\t\t\tconst live = latest?.wallets.find(\n\t\t\t\t\t(w) => w.id === placeholder.id && !w.isPlaceholder,\n\t\t\t\t);\n\t\t\t\tif (live) return live.disconnect();\n\t\t\t\tstore.forgetWallet(placeholder.id);\n\t\t\t},\n\t\t});\n\n\t\tconst settleWithState = (\n\t\t\twallet: BaseWallet | WalletConnectWallet,\n\t\t): BaseWallet | WalletConnectWallet => {\n\t\t\tconst existing = wrapped.get(wallet);\n\t\t\tif (existing) return existing;\n\t\t\tif (wallet.isPlaceholder) {\n\t\t\t\tconst deferred = deferToLive(wallet);\n\t\t\t\twrapped.set(wallet, deferred);\n\t\t\t\treturn deferred;\n\t\t\t}\n\t\t\tif (!isInjectedWallet(wallet)) return wallet;\n\t\t\tconst settled: BaseWallet = {\n\t\t\t\t...wallet,\n\t\t\t\tconnect: async (options) => {\n\t\t\t\t\tif (closed) throw abortedError(wallet.id, \"connect\");\n\t\t\t\t\tawait wallet.connect(options);\n\t\t\t\t\tsupersede(wallet.id, true);\n\t\t\t\t\tawait whenState(wallet.id, true);\n\t\t\t\t},\n\t\t\t\tdisconnect: async () => {\n\t\t\t\t\tif (closed) throw abortedError(wallet.id, \"disconnect\");\n\t\t\t\t\tawait wallet.disconnect();\n\t\t\t\t\tsupersede(wallet.id, false);\n\t\t\t\t\tawait whenState(wallet.id, false);\n\t\t\t\t},\n\t\t\t};\n\t\t\twrapped.set(wallet, settled);\n\t\t\treturn settled;\n\t\t};\n\n\t\tconst registryReads$ = createRegistryReads$().pipe(\n\t\t\tshareReplay({ bufferSize: 1, refCount: true }),\n\t\t);\n\t\tconst walletConnect$ = kc.walletConnect\n\t\t\t?.getWallet$({ config: kc, store, registryReads$ })\n\t\t\t.pipe(shareReplay({ bufferSize: 1, refCount: true }));\n\t\tconst liveWallets$ = getWallets$(kc, store, registryReads$, walletConnect$);\n\t\tconst accountFrames$ = getAccounts$(kc, liveWallets$);\n\t\tconst liveAccounts$ = accountFrames$.pipe(\n\t\t\tmap(({ accounts }) => accounts.map(asLive)),\n\t\t);\n\n\t\tconst isDiscovering$ = concat(\n\t\t\tof(true),\n\t\t\tregistryReads$.pipe(ignoreElements()),\n\t\t\t(walletConnect$ ?? EMPTY).pipe(take(1), ignoreElements()),\n\t\t\tliveWallets$.pipe(\n\t\t\t\ttake(1),\n\t\t\t\tmap(() => false),\n\t\t\t),\n\t\t).pipe(shareReplay({ bufferSize: 1, refCount: true }));\n\n\t\tconst hydrationSettled$ = combineLatest([\n\t\t\tliveWallets$,\n\t\t\taccountFrames$.pipe(startWith(noAnswerYet)),\n\t\t\tisDiscovering$,\n\t\t\treconnectCandidates$(store),\n\t\t]).pipe(\n\t\t\tmap(([wallets, { accounts, answered }, isDiscovering, remembered]) =>\n\t\t\t\tcachedWallets.every((cached) => {\n\t\t\t\t\tconst wallet = wallets.find((w) => w.id === cached.id);\n\t\t\t\t\tif (!wallet) return !isDiscovering;\n\t\t\t\t\treturn (\n\t\t\t\t\t\tcached.status !== \"connecting\" ||\n\t\t\t\t\t\treconnectSettled(cached, wallet, {\n\t\t\t\t\t\t\taccounts,\n\t\t\t\t\t\t\tanswered,\n\t\t\t\t\t\t\tcachedAccounts,\n\t\t\t\t\t\t\tremembered,\n\t\t\t\t\t\t})\n\t\t\t\t\t);\n\t\t\t\t}),\n\t\t\t),\n\t\t\tdebounceTime(0, asapScheduler),\n\t\t\tdistinctUntilChanged(),\n\t\t);\n\n\t\t// Apply hydration buffer to wallets\n\t\tconst bufferedWallets$ = createHydrationBuffer(\n\t\t\tcachedWallets,\n\t\t\tliveWallets$.pipe(map((wallets) => wallets.map(asLive))),\n\t\t\tkc.hydrationGracePeriod,\n\t\t\tkc.hydrationTimeout,\n\t\t\t(w) => w.id,\n\t\t\thydrationSettled$,\n\t\t\t(live, cached) => {\n\t\t\t\tconst status = sessionRestoring(live, cached)\n\t\t\t\t\t? \"connecting\"\n\t\t\t\t\t: live.status;\n\t\t\t\treturn {\n\t\t\t\t\t...live,\n\t\t\t\t\tstatus,\n\t\t\t\t\tisConnected: status === \"connected\",\n\t\t\t\t\ticon: cached.icon || getCachedIcon(cached.id) || live.icon,\n\t\t\t\t};\n\t\t\t},\n\t\t\t// Transform cached-only items: add icon from localStorage cache\n\t\t\t(cached) => ({\n\t\t\t\t...cached,\n\t\t\t\ticon: cached.icon || getCachedIcon(cached.id) || \"\",\n\t\t\t}),\n\t\t);\n\n\t\t// Apply hydration buffer to accounts\n\t\tconst bufferedAccounts$ = createAccountHydrationBuffer(\n\t\t\tcachedAccounts,\n\t\t\tliveAccounts$,\n\t\t\tkc.hydrationGracePeriod,\n\t\t\tkc.hydrationTimeout,\n\t\t\t(a) => a.walletId,\n\t\t\thydrationSettled$,\n\t\t);\n\n\t\t// Share the buffered streams so the main and persistence subscriptions\n\t\t// below reuse a single hydration pipeline (timers, isHydrating state)\n\t\t// instead of running the buffering twice.\n\t\tconst sharedWallets$ = bufferedWallets$.pipe(\n\t\t\tshareReplay({ bufferSize: 1, refCount: true }),\n\t\t);\n\t\tconst sharedAccounts$ = bufferedAccounts$.pipe(\n\t\t\tshareReplay({ bufferSize: 1, refCount: true }),\n\t\t);\n\n\t\t// Combine buffered wallets and accounts\n\t\tconst subscription = combineLatest({\n\t\t\twallets: sharedWallets$,\n\t\t\taccounts: sharedAccounts$,\n\t\t\tisDiscovering: isDiscovering$,\n\t\t})\n\t\t\t.pipe(\n\t\t\t\tmap(({ wallets, accounts, isDiscovering }) => {\n\t\t\t\t\tif (kc.debug) {\n\t\t\t\t\t\tconsole.debug(\"[kheopskit] hydration state\", {\n\t\t\t\t\t\t\twalletsHydrating: wallets.isHydrating,\n\t\t\t\t\t\t\taccountsHydrating: accounts.isHydrating,\n\t\t\t\t\t\t\tisDiscovering,\n\t\t\t\t\t\t\twalletsConnected: wallets.items.filter((w) => w.isConnected)\n\t\t\t\t\t\t\t\t.length,\n\t\t\t\t\t\t\twalletsTotal: wallets.items.length,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\t// Sort on every emission with the same comparators used for the\n\t\t\t\t\t// cached initial snapshot. The hydration buffers append cached-only\n\t\t\t\t\t// items after live ones (and reconnects land out of order), so\n\t\t\t\t\t// without this the list visibly reorders as wallets come back.\n\t\t\t\t\treturn {\n\t\t\t\t\t\tconfig: kc,\n\t\t\t\t\t\twallets: [...wallets.items].sort(sortWallets).map(settleWithState),\n\t\t\t\t\t\taccounts: [...accounts.items].sort(sortAccounts),\n\t\t\t\t\t\tisHydrating: wallets.isHydrating || accounts.isHydrating,\n\t\t\t\t\t\tisDiscovering,\n\t\t\t\t\t};\n\t\t\t\t}),\n\t\t\t\tdebounceTime(0, asapScheduler),\n\t\t\t\tdistinctUntilChanged(statesEqual),\n\t\t\t\ttap((state) => {\n\t\t\t\t\tlatest = state;\n\t\t\t\t\tfor (const check of liveWaiters) check(state);\n\t\t\t\t\tfor (const waiter of waiters) settleIn(waiter, state);\n\t\t\t\t}),\n\t\t\t)\n\t\t\t.subscribe(subscriber);\n\n\t\t// Persist state snapshot when hydration completes and state stabilizes\n\t\tconst persistSub = combineLatest({\n\t\t\twallets: sharedWallets$,\n\t\t\taccounts: sharedAccounts$,\n\t\t})\n\t\t\t.pipe(\n\t\t\t\t// Wait for hydration to complete\n\t\t\t\tfilter(\n\t\t\t\t\t({ wallets, accounts }) =>\n\t\t\t\t\t\t!wallets.isHydrating && !accounts.isHydrating,\n\t\t\t\t),\n\t\t\t\t// Debounce to avoid excessive writes\n\t\t\t\tdebounceTime(1000),\n\t\t\t\t// Only persist if the serialized snapshot would actually change.\n\t\t\t\t// Compare the persisted fields (not just ids): an Ethereum chain switch\n\t\t\t\t// keeps the same account id but changes the cached chainId, so an\n\t\t\t\t// id-only comparator would skip persisting it.\n\t\t\t\tdistinctUntilChanged((prev, curr) => {\n\t\t\t\t\tconst prevWalletKeys = prev.wallets.items.map(persistedWalletKey);\n\t\t\t\t\tconst currWalletKeys = curr.wallets.items.map(persistedWalletKey);\n\t\t\t\t\tconst prevAccountKeys = prev.accounts.items.map(accountChangeKey);\n\t\t\t\t\tconst currAccountKeys = curr.accounts.items.map(accountChangeKey);\n\t\t\t\t\treturn (\n\t\t\t\t\t\tarraysEqual(prevWalletKeys, currWalletKeys) &&\n\t\t\t\t\t\tarraysEqual(prevAccountKeys, currAccountKeys)\n\t\t\t\t\t);\n\t\t\t\t}),\n\t\t\t)\n\t\t\t.subscribe(({ wallets, accounts }) => {\n\t\t\t\tconst snapshot = persistedSnapshot(\n\t\t\t\t\twallets.items,\n\t\t\t\t\taccounts.items,\n\t\t\t\t\tstore.getCachedState(),\n\t\t\t\t);\n\n\t\t\t\tif (kc.debug) {\n\t\t\t\t\tconsole.debug(\"[kheopskit] persisting state snapshot:\", {\n\t\t\t\t\t\twallets: snapshot.wallets.length,\n\t\t\t\t\t\taccounts: snapshot.accounts.length,\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\tstore.setCachedState(snapshot.wallets, snapshot.accounts);\n\n\t\t\t\t// Cache wallet icons in localStorage (separate from cookies for size)\n\t\t\t\tconst icons: Record<string, string> = {};\n\t\t\t\tfor (const wallet of wallets.items) {\n\t\t\t\t\tif (wallet.icon) {\n\t\t\t\t\t\ticons[wallet.id] = wallet.icon;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tsetCachedIcons(icons);\n\t\t\t});\n\n\t\treturn () => {\n\t\t\tsubscription.unsubscribe();\n\t\t\tpersistSub.unsubscribe();\n\t\t\tclosed = true;\n\t\t\tfor (const waiter of waiters) abandon(waiter);\n\t\t\tfor (const check of liveWaiters) check(undefined);\n\t\t};\n\t}).pipe(\n\t\tlogObservable(\"kheopskit$\", { enabled: kc.debug, printValue: true }),\n\t\tshareReplay({ bufferSize: 1, refCount: true }),\n\t\t// The runtime objects are the concrete per-plugin wallet/account types;\n\t\t// recover the precise KheopskitState<P> the caller's plugins imply.\n\t) as unknown as Observable<KheopskitState<P>>;\n};\n\ntype StateWaiter = {\n\twalletId: WalletId;\n\tisConnected: boolean;\n\tresolve: () => void;\n\treject: (error: unknown) => void;\n};\n\n// AppKit restores a cached WalletConnect session on its own and reports nothing\n// until it has; an injected wallet reports its attempt from its first emission.\nconst sessionRestoring = (\n\tlive: BaseWallet | WalletConnectWallet,\n\tcached: BaseWallet | WalletConnectWallet,\n): boolean =>\n\tisWalletConnectWallet(live) &&\n\tlive.status === \"disconnected\" &&\n\tcached.status === \"connecting\";\n\nconst flagged = new WeakMap<object, object>();\n\nconst asLive = <T extends object>(item: T): T & { isPlaceholder: false } => {\n\tconst existing = flagged.get(item);\n\tif (existing) return existing as T & { isPlaceholder: false };\n\tconst live = { ...item, isPlaceholder: false as const };\n\tflagged.set(item, live);\n\treturn live;\n};\n\nconst noAnswerYet: AccountsFrame = { accounts: [], answered: [] };\n\n/**\n * A remembered wallet that reads disconnected without an error is still\n * waiting for its reconnect: getWallets$ emits the wallet list before its\n * connect() flips the status to connecting.\n */\nconst reconnectSettled = (\n\tcached: BaseWallet | WalletConnectWallet,\n\twallet: BaseWallet | WalletConnectWallet,\n\tlive: AccountsFrame & {\n\t\tcachedAccounts: BaseWalletAccount[];\n\t\tremembered: WalletId[];\n\t},\n): boolean => {\n\tconst status = sessionRestoring(wallet, cached)\n\t\t? \"connecting\"\n\t\t: wallet.status;\n\tif (status === \"connecting\") return false;\n\tif (status === \"disconnected\")\n\t\treturn wallet.error !== undefined || !live.remembered.includes(cached.id);\n\treturn (\n\t\tlive.answered.includes(cached.id) ||\n\t\t!live.cachedAccounts.some((a) => a.walletId === cached.id) ||\n\t\tlive.accounts.some((a) => a.walletId === cached.id)\n\t);\n};\n\n/**\n * A wallet still connecting keeps its previous cache entry and accounts:\n * written live it would read isConnected: false with no accounts, and the\n * next load would hydrate it as disconnected without placeholders while its\n * reconnect runs.\n */\nconst persistedSnapshot = (\n\twallets: (BaseWallet | WalletConnectWallet)[],\n\taccounts: BaseWalletAccount[],\n\tprevious: { wallets: CachedWallet[]; accounts: CachedAccount[] },\n): { wallets: CachedWallet[]; accounts: CachedAccount[] } => {\n\tconst connecting = new Set(\n\t\twallets.filter((w) => w.status === \"connecting\").map((w) => w.id),\n\t);\n\tconst connected = new Set(\n\t\twallets.filter((w) => w.isConnected).map((w) => w.id),\n\t);\n\tconst previousWallets = new Map(previous.wallets.map((w) => [w.id, w]));\n\treturn {\n\t\twallets: wallets.map(\n\t\t\t(w) =>\n\t\t\t\t(connecting.has(w.id) && previousWallets.get(w.id)) ||\n\t\t\t\tserializeWallet(w),\n\t\t),\n\t\taccounts: [\n\t\t\t...accounts\n\t\t\t\t.filter((a) => connected.has(a.walletId))\n\t\t\t\t.map(serializeAccount),\n\t\t\t...previous.accounts.filter((a) => connecting.has(a.walletId)),\n\t\t],\n\t};\n};\n\nconst arraysEqual = (a: string[], b: string[]) =>\n\ta.length === b.length && a.every((v, i) => v === b[i]);\n\n// Mutable per-platform account fields that can change without the account id\n// changing. Declared locally (not imported from the platform packages) so this\n// core entry stays free of platform SDK types — see check:isolation.\ntype EthereumAccountFields = { chainId?: number };\ntype PolkadotAccountFields = { type?: string };\ntype SolanaAccountFields = { chains?: string[] };\n\n/**\n * A signature of an account covering its id, its name, plus the\n * platform-specific fields that can change without the id changing (Ethereum\n * chainId, Polkadot key type, Solana clusters). Used to detect both UI-relevant\n * changes and changes worth re-persisting, so the two comparators can't drift\n * apart.\n */\nconst accountChangeKey = (account: BaseWalletAccount): string =>\n\t`${account.name ?? \"\"}|${accountPlatformKey(account)}`;\n\nconst accountPlatformKey = (account: BaseWalletAccount): string => {\n\tswitch (account.platform) {\n\t\tcase \"ethereum\":\n\t\t\treturn `${account.id}|${(account as EthereumAccountFields).chainId ?? \"\"}`;\n\t\tcase \"polkadot\":\n\t\t\treturn `${account.id}|${(account as PolkadotAccountFields).type ?? \"\"}`;\n\t\tcase \"solana\":\n\t\t\treturn `${account.id}|${((account as SolanaAccountFields).chains ?? []).join(\",\")}`;\n\t\tdefault:\n\t\t\treturn account.id;\n\t}\n};\n\n/** Platforms a wallet's live session carries (only the WalletConnect connector). */\nconst walletPlatforms = (wallet: BaseWallet | WalletConnectWallet): string =>\n\tisWalletConnectWallet(wallet) ? wallet.platforms.join(\",\") : \"\";\n\n/** Fields persisted to the cache for a wallet (icon is stored separately). */\nconst walletPersistKey = (wallet: BaseWallet | WalletConnectWallet): string =>\n\t`${wallet.id}|${wallet.isConnected ? 1 : 0}|${wallet.name}`;\n\n/**\n * What decides a cache write: the persisted fields plus `status`, because a\n * wallet whose kept entry was written while connecting must be rewritten live\n * once its reconnect fails, and `isConnected` reads false on both sides.\n */\nconst persistedWalletKey = (wallet: BaseWallet | WalletConnectWallet): string =>\n\t`${walletPersistKey(wallet)}|${wallet.status}`;\n\n/**\n * UI-significant signature of a wallet: the persisted fields plus icon and the\n * WalletConnect connector's `platforms` array, which drive what the UI shows but\n * aren't part of the id (icon and platforms can arrive asynchronously after\n * connect without isConnected flipping).\n */\nconst walletUiKey = (wallet: BaseWallet | WalletConnectWallet): string =>\n\t`${walletPersistKey(wallet)}|${wallet.status}|${wallet.error?.code ?? \"\"}|${wallet.icon}|${walletPlatforms(wallet)}`;\n\n/**\n * Equality check for KheopskitState to prevent unnecessary emissions. Compares\n * the UI-significant signature of every wallet and account, in order.\n */\nconst statesEqual = (a: KheopskitState, b: KheopskitState): boolean =>\n\ta.isHydrating === b.isHydrating &&\n\ta.isDiscovering === b.isDiscovering &&\n\ta.wallets.length === b.wallets.length &&\n\ta.accounts.length === b.accounts.length &&\n\ta.wallets.every((w, i) => {\n\t\tconst other = b.wallets[i];\n\t\treturn (\n\t\t\t!!other &&\n\t\t\tw.isPlaceholder === other.isPlaceholder &&\n\t\t\twalletUiKey(w) === walletUiKey(other)\n\t\t);\n\t}) &&\n\ta.accounts.every((acc, i) => {\n\t\tconst other = b.accounts[i];\n\t\treturn (\n\t\t\t!!other &&\n\t\t\tacc.isPlaceholder === other.isPlaceholder &&\n\t\t\taccountChangeKey(acc) === accountChangeKey(other)\n\t\t);\n\t});\n","import type { WalletId } from \"../utils/WalletId\";\nimport { KheopskitError } from \"./errors\";\nimport type { Liveness, LivePipeline, PipelineEnd } from \"./livePipeline\";\nimport type { ConnectOptions, KheopskitState } from \"./types\";\n\nexport type WalletActions = {\n\tconnect: (options?: ConnectOptions) => Promise<void>;\n\tdisconnect: () => Promise<void>;\n};\n\nconst didNotRun: Record<PipelineEnd, string> = {\n\taborted: \"was aborted\",\n\tunheld:\n\t\t\"was called while nothing subscribes this kheopskit instance's kheopskit$ (a mounted, visible KheopskitProvider subscribes it)\",\n\terrored: \"did not run because the pipeline stopped with an error\",\n\tcompleted: \"did not run because the pipeline completed\",\n};\n\nconst abortedError = (\n\twalletId: WalletId,\n\toperation: \"connect\" | \"disconnect\",\n\tend: PipelineEnd,\n) =>\n\tnew KheopskitError(\n\t\t\"ABORTED\",\n\t\t`${operation} of wallet ${walletId} ${didNotRun[end]}`,\n\t\t{ walletId },\n\t);\n\nconst whenLiveAfterTheCallersTask = async (\n\tpipeline: LivePipeline<KheopskitState>,\n\tsignal: AbortSignal | undefined,\n): Promise<Liveness<KheopskitState>> => {\n\tawait Promise.resolve();\n\treturn pipeline.whenLive(signal);\n};\n\nexport const walletActions = (\n\tpipeline: LivePipeline<KheopskitState>,\n\twalletId: WalletId,\n): WalletActions => {\n\tconst liveWallet = async (\n\t\toperation: \"connect\" | \"disconnect\",\n\t\tsignal?: AbortSignal,\n\t) => {\n\t\tconst liveness = await whenLiveAfterTheCallersTask(pipeline, signal);\n\t\tif (liveness.end) throw abortedError(walletId, operation, liveness.end);\n\t\tconst wallet = liveness.state.wallets.find(\n\t\t\t(candidate) => candidate.id === walletId,\n\t\t);\n\t\tif (!wallet) throw new Error(`[kheopskit] no wallet ${walletId}`);\n\t\treturn wallet;\n\t};\n\treturn {\n\t\tconnect: async (options) =>\n\t\t\t(await liveWallet(\"connect\", options?.signal)).connect(options),\n\t\tdisconnect: async () => (await liveWallet(\"disconnect\")).disconnect(),\n\t};\n};\n\ntype Wallet = KheopskitState[\"wallets\"][number];\n\nexport const createPresenter = (pipeline: LivePipeline<KheopskitState>) => {\n\tconst presentedStates = new WeakMap<KheopskitState, KheopskitState>();\n\tconst presentedWallets = new WeakMap<Wallet, Wallet>();\n\tconst presentWallet = (wallet: Wallet): Wallet => {\n\t\tlet live = presentedWallets.get(wallet);\n\t\tif (!live) {\n\t\t\tlive = { ...wallet, ...walletActions(pipeline, wallet.id) };\n\t\t\tpresentedWallets.set(wallet, live);\n\t\t}\n\t\treturn live;\n\t};\n\treturn (state: KheopskitState): KheopskitState => {\n\t\tlet live = presentedStates.get(state);\n\t\tif (!live) {\n\t\t\tlive = { ...state, wallets: state.wallets.map(presentWallet) };\n\t\t\tpresentedStates.set(state, live);\n\t\t}\n\t\treturn live;\n\t};\n};\n","import { Observable } from \"rxjs\";\n\nexport type PipelineEnd = \"aborted\" | \"unheld\" | \"errored\" | \"completed\";\n\n/** The running pipeline's state, or why it cannot serve an action. */\nexport type Liveness<T> = { state: T; end?: undefined } | { end: PipelineEnd };\n\nexport type LivePipeline<T extends {}> = {\n\t/** Subscribing holds the pipeline; it runs while at least one holder stays. */\n\tobservable$: Observable<T>;\n\twhenLivePicks: <R extends {}>(\n\t\tpick: (state: T) => R | undefined,\n\t\tsignal?: AbortSignal,\n\t) => Promise<Liveness<R>>;\n\t/**\n\t * The current run's state: its latest value, or its first emission once it\n\t * arrives. Ends `unheld` while nothing holds the pipeline, without starting\n\t * it, `errored` or `completed` once the run ended that way, and `aborted`\n\t * when `signal` fires first.\n\t */\n\twhenLive: (signal?: AbortSignal) => Promise<Liveness<T>>;\n};\n\nexport const createLivePipeline = <T extends {}>(\n\tsource$: Observable<T>,\n): LivePipeline<T> => {\n\tlet holders = 0;\n\tlet run = 0;\n\tlet emittedRun = 0;\n\tlet latestValue: T | undefined;\n\tlet ended: PipelineEnd | undefined;\n\tconst waiters = new Set<(liveness: Liveness<T>) => void>();\n\n\tconst notifyWaiters = (liveness: Liveness<T>) => {\n\t\tfor (const waiter of waiters) waiter(liveness);\n\t};\n\n\tconst observable$ = new Observable<T>((subscriber) => {\n\t\tif (holders++ === 0) {\n\t\t\trun++;\n\t\t\tended = undefined;\n\t\t}\n\t\tconst thisRun = run;\n\t\tconst subscription = source$.subscribe({\n\t\t\tnext: (value) => {\n\t\t\t\tlatestValue = value;\n\t\t\t\temittedRun = thisRun;\n\t\t\t\tnotifyWaiters({ state: value });\n\t\t\t\tsubscriber.next(value);\n\t\t\t},\n\t\t\terror: (error) => {\n\t\t\t\tended = \"errored\";\n\t\t\t\tsubscriber.error(error);\n\t\t\t},\n\t\t\tcomplete: () => {\n\t\t\t\tended = \"completed\";\n\t\t\t\tsubscriber.complete();\n\t\t\t},\n\t\t});\n\t\treturn () => {\n\t\t\tsubscription.unsubscribe();\n\t\t\tif (--holders === 0) notifyWaiters({ end: ended ?? \"unheld\" });\n\t\t};\n\t});\n\n\tconst whenLivePicks = async <R extends {}>(\n\t\tpick: (state: T) => R | undefined,\n\t\tsignal?: AbortSignal,\n\t): Promise<Liveness<R>> => {\n\t\tif (signal?.aborted) return { end: \"aborted\" };\n\t\tif (ended) return { end: ended };\n\t\tif (holders === 0) return { end: \"unheld\" };\n\t\tconst current = emittedRun === run ? pick(latestValue as T) : undefined;\n\t\tif (current !== undefined) return { state: current };\n\t\treturn new Promise((resolve) => {\n\t\t\tconst settle = (liveness: Liveness<R>) => {\n\t\t\t\twaiters.delete(observe);\n\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\tresolve(liveness);\n\t\t\t};\n\t\t\tconst observe = (liveness: Liveness<T>) => {\n\t\t\t\tif (liveness.end) return settle({ end: liveness.end });\n\t\t\t\tconst picked = pick(liveness.state);\n\t\t\t\tif (picked !== undefined) settle({ state: picked });\n\t\t\t};\n\t\t\tconst onAbort = () => settle({ end: \"aborted\" });\n\t\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\twaiters.add(observe);\n\t\t});\n\t};\n\n\tconst whenLive = (signal?: AbortSignal) =>\n\t\twhenLivePicks((state) => state, signal);\n\n\treturn { observable$, whenLivePicks, whenLive };\n};\n","import { defer, map, type Observable, ReplaySubject, share } from \"rxjs\";\nimport {\n\tparseWalletAccountId,\n\ttype WalletAccountId,\n} from \"../utils/WalletAccountId\";\nimport type { WalletId } from \"../utils/WalletId\";\nimport { resolveConfig } from \"./config\";\nimport { accountUnavailableError, KheopskitError } from \"./errors\";\nimport { kheopskitRun$ } from \"./kheopskit\";\nimport {\n\tcreatePresenter,\n\ttype WalletActions,\n\twalletActions,\n} from \"./liveActions\";\nimport { createLivePipeline, type PipelineEnd } from \"./livePipeline\";\nimport { createKheopskitStore } from \"./store\";\nimport type {\n\tAccountOf,\n\tKheopskitConfig,\n\tKheopskitPlatform,\n\tKheopskitState,\n\tKheopskitStore,\n} from \"./types\";\n\nexport type CreateKheopskitConfig<P extends readonly KheopskitPlatform[]> =\n\tOmit<Partial<KheopskitConfig<P>>, \"platforms\"> & {\n\t\t/** Platform plugins, e.g. `[polkadot(), solana()]`. Required. */\n\t\tplatforms: P;\n\t};\n\n/** Where the instance persists. Exactly one source; both cannot compile. */\nexport type CreateKheopskitOptions =\n\t| {\n\t\t\t/** Store the instance reads the cache from and persists into. */\n\t\t\tstore: KheopskitStore;\n\t\t\tssr?: never;\n\t }\n\t| {\n\t\t\tstore?: never;\n\t\t\t/**\n\t\t\t * Persist in cookies, so a server render can read them through\n\t\t\t * `ssrCookies`. Default: localStorage.\n\t\t\t */\n\t\t\tssr?: boolean;\n\t };\n\ntype WaitForAccount<A> = (\n\taccountId: WalletAccountId,\n\toptions?: { signal?: AbortSignal },\n) => Promise<A>;\n\n/**\n * One kheopskit instance. Subscribing `kheopskit$` holds its pipeline: it\n * runs while at least one subscriber stays, and every subscriber shares that\n * one run. When the last subscriber leaves, it stops. The next subscriber\n * starts a new run, which re-reads the cache.\n *\n * A wallet's `connect` and `disconnect`, read from any emission, act on the\n * run that is live when they are called. They wait for a restarted run's\n * first emission, reject `ABORTED` while nothing subscribes, and never start\n * the pipeline themselves.\n */\nexport type Kheopskit<P extends readonly KheopskitPlatform[]> = {\n\treadonly kheopskit$: Observable<KheopskitState<P>>;\n\t/** Created on first use. Destructuring it creates nothing. */\n\treadonly store: KheopskitStore;\n\t/**\n\t * Resolves with the account once the live run lists it as a live account,\n\t * at once when it already does. Waits while the run hydrates, while\n\t * discovery runs and has not listed the account's wallet, while that\n\t * wallet is `connecting`, and while it is connected but lists no account\n\t * yet. Rejects `ACCOUNT_UNAVAILABLE` once none of these holds and the\n\t * account is still not live. A connected wallet that lists no accounts\n\t * keeps the wait open until `signal` fires or the last subscriber leaves.\n\t * Rejects `ABORTED` when nothing subscribes `kheopskit$` by the end of the\n\t * calling task, when the last subscriber leaves, or when `signal` fires. It\n\t * never starts or holds the pipeline.\n\t */\n\treadonly waitForAccount: WaitForAccount<\n\t\tExclude<AccountOf<P[number]>, { isPlaceholder: true }>\n\t>;\n};\n\ntype LiveAccountOf<S extends KheopskitState> = Exclude<\n\tS[\"accounts\"][number],\n\t{ isPlaceholder: true }\n>;\n\ntype AccountLookup<A> =\n\t| { status: \"live\"; account: A }\n\t| { status: \"unavailable\" };\n\nconst lookUpAccount = <S extends KheopskitState>(\n\tstate: S,\n\taccountId: WalletAccountId,\n\twalletId: WalletId,\n): AccountLookup<LiveAccountOf<S>> | undefined => {\n\tconst account = state.accounts.find(\n\t\t(candidate): candidate is LiveAccountOf<S> =>\n\t\t\tcandidate.id === accountId && !candidate.isPlaceholder,\n\t);\n\tif (account) return { status: \"live\", account };\n\treturn mayStillList(state, walletId) ? undefined : { status: \"unavailable\" };\n};\n\nconst mayStillList = (state: KheopskitState, walletId: WalletId) => {\n\tif (state.isHydrating) return true;\n\tconst wallet = state.wallets.find((candidate) => candidate.id === walletId);\n\tif (!wallet) return state.isDiscovering;\n\tif (wallet.status === \"connecting\") return true;\n\treturn (\n\t\twallet.isConnected &&\n\t\t!state.accounts.some((candidate) => candidate.walletId === walletId)\n\t);\n};\n\nconst didNotWait: Record<PipelineEnd, string> = {\n\taborted: \"was aborted\",\n\tunheld:\n\t\t\"was called while nothing subscribes this kheopskit instance's kheopskit$ (a mounted, visible KheopskitProvider subscribes it)\",\n\terrored: \"did not run because the pipeline stopped with an error\",\n\tcompleted: \"did not run because the pipeline completed\",\n};\n\ntype KheopskitInternals = {\n\tpresent: (state: KheopskitState) => KheopskitState;\n\twalletActions: (walletId: WalletId) => WalletActions;\n};\n\nconst internals = new WeakMap<object, KheopskitInternals>();\n\nexport const createInstance = <T extends KheopskitState>(\n\trun$: () => Observable<T>,\n\tstore: KheopskitStore,\n): {\n\treadonly kheopskit$: Observable<T>;\n\treadonly store: KheopskitStore;\n\treadonly waitForAccount: WaitForAccount<LiveAccountOf<T>>;\n} => {\n\tconst pipeline = createLivePipeline(\n\t\tdefer(run$).pipe(\n\t\t\tshare({\n\t\t\t\tconnector: () => new ReplaySubject(1),\n\t\t\t\tresetOnError: true,\n\t\t\t\tresetOnComplete: true,\n\t\t\t\tresetOnRefCountZero: true,\n\t\t\t}),\n\t\t),\n\t);\n\tconst present = createPresenter(pipeline);\n\tconst waitForAccount: WaitForAccount<LiveAccountOf<T>> = async (\n\t\taccountId,\n\t\t{ signal } = {},\n\t) => {\n\t\tconst { walletId } = parseWalletAccountId(accountId);\n\t\tawait Promise.resolve();\n\t\tconst found = await pipeline.whenLivePicks(\n\t\t\t(state) => lookUpAccount(state, accountId, walletId),\n\t\t\tsignal,\n\t\t);\n\t\tif (found.end)\n\t\t\tthrow new KheopskitError(\n\t\t\t\t\"ABORTED\",\n\t\t\t\t`waitForAccount of account ${accountId} ${didNotWait[found.end]}`,\n\t\t\t\t{ walletId },\n\t\t\t);\n\t\tif (found.state.status === \"unavailable\")\n\t\t\tthrow accountUnavailableError(accountId, walletId);\n\t\treturn found.state.account;\n\t};\n\tconst kit = {\n\t\tkheopskit$: pipeline.observable$.pipe(map(present)) as Observable<T>,\n\t\tstore,\n\t\twaitForAccount,\n\t};\n\tinternals.set(kit, {\n\t\tpresent,\n\t\twalletActions: (walletId) => walletActions(pipeline, walletId),\n\t});\n\treturn kit;\n};\n\nexport const kheopskitInternals = (\n\tkit: Kheopskit<readonly KheopskitPlatform[]>,\n): KheopskitInternals => {\n\tconst found = internals.get(kit);\n\tif (!found) throw new Error(\"[kheopskit] not a kheopskit instance\");\n\treturn found;\n};\n\nconst lazyStore = (create: () => KheopskitStore): KheopskitStore => ({\n\tobservable: defer(() => create().observable),\n\trememberWallet: (walletId) => create().rememberWallet(walletId),\n\tforgetWallet: (walletId) => create().forgetWallet(walletId),\n\tgetCachedState: () => create().getCachedState(),\n\tsetCachedState: (wallets, accounts) =>\n\t\tcreate().setCachedState(wallets, accounts),\n\tdestroy: () => create().destroy(),\n});\n\nconst inertOnTheServer = (store: KheopskitStore): KheopskitStore =>\n\ttypeof window === \"undefined\"\n\t\t? {\n\t\t\t\t...store,\n\t\t\t\trememberWallet: () => {},\n\t\t\t\tforgetWallet: () => {},\n\t\t\t\tsetCachedState: () => {},\n\t\t\t}\n\t\t: store;\n\n/**\n * Creates one kheopskit instance: `kheopskit$`, the state stream every\n * subscriber shares, and `store`, which it reads the cache from and persists\n * into. Subscribe once at app start to keep it running for the page's\n * lifetime.\n *\n * @example\n * ```ts\n * export const { kheopskit$, store } = createKheopskit({ platforms: [polkadot()] });\n * kheopskit$.subscribe(render);\n * ```\n */\nexport const createKheopskit = <\n\tconst P extends readonly [KheopskitPlatform, ...KheopskitPlatform[]],\n>(\n\tconfig: CreateKheopskitConfig<P>,\n\toptions: CreateKheopskitOptions = {},\n): Kheopskit<P> => {\n\tconst { storageKey } = resolveConfig(config);\n\tlet created: KheopskitStore | undefined;\n\tconst store = () => {\n\t\tcreated ??=\n\t\t\toptions.store ??\n\t\t\tinertOnTheServer(\n\t\t\t\tcreateKheopskitStore({\n\t\t\t\t\tssrCookies: options.ssr ? \"\" : undefined,\n\t\t\t\t\tstorageKey,\n\t\t\t\t}),\n\t\t\t);\n\t\treturn created;\n\t};\n\treturn createInstance(\n\t\t() => kheopskitRun$(config, { store: store() }),\n\t\toptions.store ?? lazyStore(store),\n\t);\n};\n"],"mappings":";;;;;;;;;;;AAQA,MAAa,sBAAsB;AAEnC,MAAM,WAAW;CAChB,eAAe;CACf,OAAO;CACP,YAAY;CACZ,sBAAsB;CACtB,kBAAkB;AACnB;AAEA,MAAa,iBAGZ,WACwB;CACxB,MAAM,YAAa,QAAQ,aAAa,CAAC;CAIzC,MAAM,mBAAoB,UAAiC,QACzD,MACA,OAAO,MAAM,YACb,MAAM,QACN,OAAQ,EAAgC,gBAAgB,UAC1D;CACA,IAAI,iBAAiB,SAAS,GAC7B,MAAM,IAAI,MACT,sNAGqB,KAAK,UAAU,gBAAgB,EAAE,qFAEvD;CAGD,IACC,QAAQ,kBAAkB,KAAA,KAC1B,OAAQ,OAAO,eACZ,eAAe,YAElB,MAAM,IAAIA,cAAAA,eACT,kBACA,sPAGD;CAGD,IAAI,UAAU,WAAW,GACxB,QAAQ,KACP,+IAED;CAGD,OAAO,OAAO,OAAO,CAAC,GAAG,UAAU,QAAQ,EAAE,UAAU,CAAC;AACzD;;;;;;;;;;;;ACzCA,MAAM,oBAAoB,UAAkB,eAA+B;CAE1E,IAAI,aAAa,YAChB,OAAOC,sBAAAA,oBAAoB,WAAW,EAAE,QAAQ;CAGjD,OAAO;AACR;AAIA,MAAa,iBACZ,WACqD;CACrD,MAAM,UAAU,YAAY;EA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Ae;CAC9C,iBAAiB,SAAS,aACzB,OAAO,CAAC,CAAC,eAAe,SAAS,QAAQ;CAC1C,eAAe,OAAO,CAAC,CAAC,QAAQ;AACjC;AAEA,MAAM,oBAAoB,UACzB,OAAO,WAAW,cACf;CACA,GAAG;CACH,sBAAsB,CAAC;CACvB,oBAAoB,CAAC;CACrB,sBAAsB,CAAC;AACxB,IACC;;;;;;;;;;;;;AAcJ,MAAa,mBAGZ,QACA,UAAkC,CAAC,MACjB;CAClB,MAAM,EAAE,eAAe,cAAc,MAAM;CAC3C,IAAI;CACJ,MAAM,cAAc;EACnB,YAAA,UACC,QAAQ,SACR,iBACC,qBAAqB;GACpB,YAAY,QAAQ,MAAM,KAAK,KAAA;GAC/B;EACD,CAAC,CACF;EACD,OAAO;CACR;CACA,OAAO,qBACA,cAAc,QAAQ,EAAE,OAAO,MAAM,EAAE,CAAC,GAC9C,QAAQ,SAAS,UAAU,KAAK,CACjC;AACD"}
@@ -1,4 +1,4 @@
1
- import { N as WalletAccountId, c as KheopskitConfig, d as KheopskitStore, k as WalletId, l as KheopskitPlatform, s as ConnectOptions, t as AccountOf, u as KheopskitState } from "./types-C7DyeFOY.mjs";
1
+ import { N as WalletAccountId, c as KheopskitConfig, d as KheopskitStore, k as WalletId, l as KheopskitPlatform, s as ConnectOptions, t as AccountOf, u as KheopskitState } from "./types-BGeGUtxz.mjs";
2
2
  import { Observable } from "rxjs";
3
3
  //#region src/utils/getCachedObservable.d.ts
4
4
  /**
@@ -106,4 +106,4 @@ declare const kheopskitInternals: (kit: Kheopskit<readonly KheopskitPlatform[]>)
106
106
  declare const createKheopskit: <const P extends readonly [KheopskitPlatform, ...KheopskitPlatform[]]>(config: CreateKheopskitConfig<P>, options?: CreateKheopskitOptions) => Kheopskit<P>;
107
107
  //#endregion
108
108
  export { createKheopskit as a, clearAllCachedObservables as c, createInstance as i, clearCachedObservable as l, CreateKheopskitOptions as n, kheopskitInternals as o, Kheopskit as r, WalletActions as s, CreateKheopskitConfig as t, clearCachedObservablesByPrefix as u };
109
- //# sourceMappingURL=instance-DTxZT9GE.d.mts.map
109
+ //# sourceMappingURL=instance-DDvZiq1L.d.mts.map
@@ -1,6 +1,6 @@
1
1
  import { n as getSafeLocalStorage } from "./storage-D3AwNgqc.mjs";
2
- import { a as CachedAccount, b as WalletConnectWallet, i as BaseWalletAccount, o as CachedWallet, r as BaseWallet } from "./types-C7DyeFOY.mjs";
3
- import { i as createInstance, l as clearCachedObservable, o as kheopskitInternals, s as WalletActions, u as clearCachedObservablesByPrefix } from "./instance-DTxZT9GE.mjs";
2
+ import { a as CachedAccount, b as WalletConnectWallet, i as BaseWalletAccount, o as CachedWallet, r as BaseWallet } from "./types-BGeGUtxz.mjs";
3
+ import { i as createInstance, l as clearCachedObservable, o as kheopskitInternals, s as WalletActions, u as clearCachedObservablesByPrefix } from "./instance-DDvZiq1L.mjs";
4
4
  //#region src/utils/hydrateState.d.ts
5
5
  /**
6
6
  * Converts a wallet to a CachedWallet for storage.
@@ -1,6 +1,6 @@
1
1
  import { n as getSafeLocalStorage } from "./storage-D3AwNgqc.js";
2
- import { a as CachedAccount, b as WalletConnectWallet, i as BaseWalletAccount, o as CachedWallet, r as BaseWallet } from "./types-C7DyeFOY.js";
3
- import { i as createInstance, l as clearCachedObservable, o as kheopskitInternals, s as WalletActions, u as clearCachedObservablesByPrefix } from "./instance-D6rAcYlp.js";
2
+ import { a as CachedAccount, b as WalletConnectWallet, i as BaseWalletAccount, o as CachedWallet, r as BaseWallet } from "./types-BGeGUtxz.js";
3
+ import { i as createInstance, l as clearCachedObservable, o as kheopskitInternals, s as WalletActions, u as clearCachedObservablesByPrefix } from "./instance-1BgEld17.js";
4
4
  //#region src/utils/hydrateState.d.ts
5
5
  /**
6
6
  * Converts a wallet to a CachedWallet for storage.
package/dist/internal.js CHANGED
@@ -1,6 +1,6 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_types = require("./types-BrMtrjs9.js");
3
- const require_instance = require("./instance-ClNA6MX-.js");
3
+ const require_instance = require("./instance-CCP7uJV3.js");
4
4
  exports.clearCachedObservable = require_types.clearCachedObservable;
5
5
  exports.clearCachedObservablesByPrefix = require_types.clearCachedObservablesByPrefix;
6
6
  exports.createInstance = require_instance.createInstance;
package/dist/internal.mjs CHANGED
@@ -1,3 +1,3 @@
1
1
  import { _ as clearCachedObservablesByPrefix, g as clearCachedObservable } from "./types-D7OWi0Td.mjs";
2
- import { c as getSafeLocalStorage, l as serializeAccount, r as kheopskitInternals, s as setCachedIcons, t as createInstance, u as serializeWallet } from "./instance-DN64bXb6.mjs";
2
+ import { c as getSafeLocalStorage, l as serializeAccount, r as kheopskitInternals, s as setCachedIcons, t as createInstance, u as serializeWallet } from "./instance-BPAvq0v7.mjs";
3
3
  export { clearCachedObservable, clearCachedObservablesByPrefix, createInstance, getSafeLocalStorage, kheopskitInternals, serializeAccount, serializeWallet, setCachedIcons };
@@ -1,4 +1,4 @@
1
- import { E as isWalletConnectWallet, N as WalletAccountId, T as isInjectedWallet, b as WalletConnectWallet, g as PolkadotAccountType, k as WalletId, l as KheopskitPlatform, m as PlaceholderWallet, p as Placeholder, r as BaseWallet } from "./types-C7DyeFOY.mjs";
1
+ import { E as isWalletConnectWallet, N as WalletAccountId, T as isInjectedWallet, b as WalletConnectWallet, g as PolkadotAccountType, k as WalletId, l as KheopskitPlatform, m as PlaceholderWallet, p as Placeholder, r as BaseWallet } from "./types-BGeGUtxz.mjs";
2
2
  import { InjectedPolkadotAccount, SignPayload } from "polkadot-api/pjs-signer";
3
3
  //#region src/utils/isSs58Address.d.ts
4
4
  /**
@@ -30,6 +30,13 @@ type PolkadotInjectedAccount = {
30
30
  */
31
31
  partOfPortfolio?: boolean;
32
32
  };
33
+ /**
34
+ * The payload polkadot-api's `TxCreator` receives, read from the installed
35
+ * version. polkadot-api v2 has no `TxCreator`, so it is `never` there.
36
+ */
37
+ type TxPayloadV1 = InjectedPolkadotAccount extends {
38
+ txCreator: (payload: infer Payload, ...rest: never[]) => unknown;
39
+ } ? Payload : never;
33
40
  /**
34
41
  * The object `window.injectedWeb3[id].enable(appName)` resolved to, typed
35
42
  * structurally (pjs-signer does not export its type). `metadata` and
@@ -56,6 +63,12 @@ type PolkadotInjected = {
56
63
  id: number;
57
64
  signature: `0x${string}`;
58
65
  }>;
66
+ /**
67
+ * Builds and signs the whole transaction from a polkadot-api `TxPayloadV1`,
68
+ * so the wallet encodes transaction extensions pjs-signer does not know.
69
+ * Only some wallets implement it.
70
+ */
71
+ createTransaction?: (payload: TxPayloadV1) => Promise<string>;
59
72
  };
60
73
  metadata?: unknown;
61
74
  provider?: unknown;
@@ -1,4 +1,4 @@
1
- import { E as isWalletConnectWallet, N as WalletAccountId, T as isInjectedWallet, b as WalletConnectWallet, g as PolkadotAccountType, k as WalletId, l as KheopskitPlatform, m as PlaceholderWallet, p as Placeholder, r as BaseWallet } from "./types-C7DyeFOY.js";
1
+ import { E as isWalletConnectWallet, N as WalletAccountId, T as isInjectedWallet, b as WalletConnectWallet, g as PolkadotAccountType, k as WalletId, l as KheopskitPlatform, m as PlaceholderWallet, p as Placeholder, r as BaseWallet } from "./types-BGeGUtxz.js";
2
2
  import { InjectedPolkadotAccount, SignPayload } from "polkadot-api/pjs-signer";
3
3
  //#region src/utils/isSs58Address.d.ts
4
4
  /**
@@ -30,6 +30,13 @@ type PolkadotInjectedAccount = {
30
30
  */
31
31
  partOfPortfolio?: boolean;
32
32
  };
33
+ /**
34
+ * The payload polkadot-api's `TxCreator` receives, read from the installed
35
+ * version. polkadot-api v2 has no `TxCreator`, so it is `never` there.
36
+ */
37
+ type TxPayloadV1 = InjectedPolkadotAccount extends {
38
+ txCreator: (payload: infer Payload, ...rest: never[]) => unknown;
39
+ } ? Payload : never;
33
40
  /**
34
41
  * The object `window.injectedWeb3[id].enable(appName)` resolved to, typed
35
42
  * structurally (pjs-signer does not export its type). `metadata` and
@@ -56,6 +63,12 @@ type PolkadotInjected = {
56
63
  id: number;
57
64
  signature: `0x${string}`;
58
65
  }>;
66
+ /**
67
+ * Builds and signs the whole transaction from a polkadot-api `TxPayloadV1`,
68
+ * so the wallet encodes transaction extensions pjs-signer does not know.
69
+ * Only some wallets implement it.
70
+ */
71
+ createTransaction?: (payload: TxPayloadV1) => Promise<string>;
59
72
  };
60
73
  metadata?: unknown;
61
74
  provider?: unknown;
package/dist/polkadot.js CHANGED
@@ -109,7 +109,9 @@ const getInjectedWalletAccounts$ = (wallet) => {
109
109
  return new rxjs.Observable((subscriber) => {
110
110
  const signPayload = injected.signer.signPayload.bind(injected.signer);
111
111
  const signRaw = injected.signer.signRaw.bind(injected.signer);
112
- const { field, factory } = getPjsSignerField();
112
+ const createTransaction = injected.signer.createTransaction?.bind(injected.signer);
113
+ const { field, factory, getAccountTxCreator } = getPjsSignerField();
114
+ const createSigner = (address, type) => createTransaction && getAccountTxCreator ? getAccountTxCreator(address, createTransaction, signRaw, type) : factory(address, signPayload, signRaw, type);
113
115
  const toAccount = (account) => {
114
116
  const { address } = account;
115
117
  const type = account.type ?? "sr25519";
@@ -120,7 +122,7 @@ const getInjectedWalletAccounts$ = (wallet) => {
120
122
  platform: "polkadot",
121
123
  walletName: wallet.name,
122
124
  walletId: wallet.id,
123
- [field]: factory(address, signPayload, signRaw, toSignerType(type)),
125
+ [field]: createSigner(address, toSignerType(type)),
124
126
  signRaw: async (data, options) => (await signRaw({
125
127
  address,
126
128
  ...encodeRawData(data, options?.type)
@@ -145,13 +147,15 @@ const getInjectedWalletAccounts$ = (wallet) => {
145
147
  /**
146
148
  * polkadot-api v3 replaced `polkadotSigner` (PolkadotSigner) with `txCreator`
147
149
  * (TxCreator). Which one the app's installed version provides is detected at
148
- * runtime so a single @kheopskit/core release supports both.
150
+ * runtime so a single @kheopskit/core release supports both. Newer v3 releases
151
+ * add `getAccountTxCreator`, which lets the wallet build the transaction.
149
152
  */
150
153
  const getPjsSignerField = () => {
151
154
  const module = polkadot_api_pjs_signer;
152
155
  if (module.getTxCreatorFromPjs) return {
153
156
  field: "txCreator",
154
- factory: module.getTxCreatorFromPjs
157
+ factory: module.getTxCreatorFromPjs,
158
+ getAccountTxCreator: module.getAccountTxCreator
155
159
  };
156
160
  if (module.getPolkadotSignerFromPjs) return {
157
161
  field: "polkadotSigner",
@@ -1 +1 @@
1
- {"version":3,"file":"polkadot.js","names":["getInjectedExtensions","getWalletId","createRegistryReads$","createInjectedWallets$","map","distinctUntilChanged","isEqual","parseWalletId","isRefusalMessage","POLKADOT_EXTENSIONS","hex","of","Observable","getWalletAccountId","pjs","KheopskitError","getWalletConnectSessionAccounts$","getCaip10Addresses","getSessionCaip10s","createPlatformAccounts$"],"sources":["../src/api/polkadot/wallets.ts","../src/api/polkadot/accounts.ts","../src/api/polkadot/plugin.ts"],"sourcesContent":["import { isEqual } from \"lodash-es\";\nimport { getInjectedExtensions } from \"polkadot-api/pjs-signer\";\nimport { distinctUntilChanged, map, type Observable } from \"rxjs\";\nimport { POLKADOT_EXTENSIONS } from \"../../utils/polkadotExtensions\";\nimport { createRegistryReads$ } from \"../../utils/registryReads\";\nimport {\n\tgetWalletId,\n\tparseWalletId,\n\ttype WalletId,\n} from \"../../utils/WalletId\";\nimport { isRefusalMessage } from \"../errors\";\nimport { createInjectedWallets$ } from \"../injectedWallets\";\nimport type { KheopskitStore } from \"../store\";\nimport type { KheopskitConfig } from \"../types\";\nimport type {\n\tPolkadotInjected,\n\tPolkadotInjectedAccount,\n\tPolkadotInjectedWallet,\n} from \"./types\";\n\ntype EnableResult = {\n\taccounts?: Partial<PolkadotInjected[\"accounts\"]>;\n\tsigner?: Partial<PolkadotInjected[\"signer\"]>;\n\tmetadata?: unknown;\n\tprovider?: unknown;\n};\n\ntype InjectedWeb3Window = {\n\tinjectedWeb3?: Record<\n\t\tstring,\n\t\t| { enable(appName: string): Promise<EnableResult | null | undefined> }\n\t\t| undefined\n\t>;\n};\n\nconst isPolkadotInjected = (\n\tinjected: EnableResult | null | undefined,\n): injected is PolkadotInjected =>\n\ttypeof injected?.accounts?.get === \"function\" &&\n\ttypeof injected.accounts.subscribe === \"function\" &&\n\ttypeof injected.signer?.signPayload === \"function\" &&\n\ttypeof injected.signer.signRaw === \"function\";\n\n/**\n * The list each extension last reported: read when its connect was granted,\n * so the emission that first shows the wallet connected already lists it, and\n * updated by every `subscribe` callback, so an accounts stream that restarts\n * resumes from the current list rather than the connect-time one.\n */\nexport const latestAccounts = new WeakMap<\n\tPolkadotInjected,\n\tPolkadotInjectedAccount[]\n>();\n\ntype InjectedWeb3Entry = NonNullable<\n\tNonNullable<InjectedWeb3Window[\"injectedWeb3\"]>[string]\n>;\n\n/**\n * The connect each extension is still answering. An extension keeps its\n * prompt open after kheopskit abandons the attempt, and a second `enable()`\n * meanwhile fails (polkadot-js: \"Pending authorisation request already\n * exists\") or resolves unauthorised (Talisman), so a new attempt joins this\n * one instead.\n */\nconst pendingConnects = new WeakMap<\n\tInjectedWeb3Entry,\n\tPromise<PolkadotInjected>\n>();\n\nconst enableExtension = async (\n\tidentifier: string,\n\tentry: InjectedWeb3Entry,\n\tappName: string,\n) => {\n\tconst injected = await entry.enable(appName);\n\tif (!isPolkadotInjected(injected))\n\t\tthrow new Error(`Unsupported extension: \"${identifier}\"`);\n\tlatestAccounts.set(injected, await injected.accounts.get());\n\treturn injected;\n};\n\nconst connectExtension = (\n\tidentifier: string,\n\tappName: string,\n): Promise<PolkadotInjected> => {\n\tconst entry = (globalThis as InjectedWeb3Window).injectedWeb3?.[identifier];\n\tif (!entry)\n\t\treturn Promise.reject(new Error(`Unavailable extension: \"${identifier}\"`));\n\tconst pending = pendingConnects.get(entry);\n\tif (pending) return pending;\n\tconst connecting = enableExtension(identifier, entry, appName);\n\tpendingConnects.set(entry, connecting);\n\tconst settle = () => pendingConnects.delete(entry);\n\tconnecting.then(settle, settle);\n\treturn connecting;\n};\n\nconst getInjectedWalletsIds = () =>\n\ttypeof window === \"undefined\"\n\t\t? []\n\t\t: getInjectedExtensions().map((name) => getWalletId(\"polkadot\", name));\n\n// The shared WalletConnect connector is emitted once by core (see\n// `getWallets$`), not per platform — so this returns only injected wallets.\nexport const getPolkadotWallets$ = (\n\tstore: KheopskitStore,\n\tconfig: Pick<KheopskitConfig, \"appName\" | \"walletConnect\">,\n\tregistryReads$: Observable<void> = createRegistryReads$(),\n) =>\n\tcreateInjectedWallets$<WalletId, PolkadotInjectedWallet, PolkadotInjected>(\n\t\tstore,\n\t\t{\n\t\t\tsources$: registryReads$.pipe(\n\t\t\t\tmap(getInjectedWalletsIds),\n\t\t\t\tdistinctUntilChanged<WalletId[]>(isEqual),\n\t\t\t),\n\t\t\tgetWalletId: (walletId) => walletId,\n\t\t\tconnect: (walletId) =>\n\t\t\t\tconnectExtension(\n\t\t\t\t\tparseWalletId(walletId).identifier,\n\t\t\t\t\tconfig.appName ||\n\t\t\t\t\t\tconfig.walletConnect?.metadata.name ||\n\t\t\t\t\t\twindow.location.hostname,\n\t\t\t\t),\n\t\t\tisUserRejection: isRefusalMessage,\n\t\t\tbuildWallet: ({\n\t\t\t\twalletId,\n\t\t\t\thandle,\n\t\t\t\tstatus,\n\t\t\t\terror,\n\t\t\t\tisConnected,\n\t\t\t\tconnect,\n\t\t\t\tdisconnect,\n\t\t\t}) => {\n\t\t\t\tconst { identifier } = parseWalletId(walletId);\n\t\t\t\tconst extInfo = POLKADOT_EXTENSIONS[identifier];\n\n\t\t\t\treturn {\n\t\t\t\t\tid: walletId,\n\t\t\t\t\ttype: \"injected\",\n\t\t\t\t\tplatform: \"polkadot\",\n\t\t\t\t\tname: extInfo?.name ?? identifier,\n\t\t\t\t\ticon: extInfo?.icon ?? \"\",\n\t\t\t\t\tsourceId: identifier,\n\t\t\t\t\textension: handle,\n\t\t\t\t\tstatus,\n\t\t\t\t\terror,\n\t\t\t\t\tisConnected,\n\t\t\t\t\tconnect,\n\t\t\t\t\tdisconnect,\n\t\t\t\t};\n\t\t\t},\n\t\t},\n\t);\n","import { hex } from \"@scure/base\";\nimport type {\n\tKeypairType,\n\tSignPayload,\n\tSignRaw,\n} from \"polkadot-api/pjs-signer\";\nimport * as pjs from \"polkadot-api/pjs-signer\";\nimport { Observable, of } from \"rxjs\";\nimport { getWalletAccountId } from \"../../utils\";\nimport { KheopskitError } from \"../errors\";\nimport {\n\tcreatePlatformAccounts$,\n\tgetCaip10Addresses,\n\tgetSessionCaip10s,\n\tgetWalletConnectSessionAccounts$,\n\ttype LiveWalletConnectWallet,\n} from \"../platformAccounts\";\nimport type {\n\tAppKitInstance,\n\tPolkadotAccountType,\n\tWalletConnectProvider,\n\tWalletConnectWallet,\n} from \"../types\";\nimport type {\n\tPolkadotAccount,\n\tPolkadotInjectedAccount,\n\tPolkadotInjectedWallet,\n\tPolkadotSignRawType,\n\tPolkadotWallet,\n} from \"./types\";\nimport { latestAccounts } from \"./wallets\";\n\ntype RawSignature = `0x${string}`;\n\nconst encodeRawData = (\n\tdata: string | Uint8Array,\n\ttype?: PolkadotSignRawType,\n): { data: string; type: PolkadotSignRawType } =>\n\ttypeof data === \"string\"\n\t\t? { data, type: type ?? \"payload\" }\n\t\t: { data: `0x${hex.encode(data)}`, type: type ?? \"bytes\" };\n\n/**\n * pjs-signer's signature-type map knows ed25519, sr25519 and ecdsa only, so an\n * `ethereum` type would get a 64-byte mock signature where ecdsa needs 65.\n */\nconst toSignerType = (type: PolkadotAccountType): KeypairType =>\n\ttype === \"ethereum\" ? \"ecdsa\" : type;\n\nconst getInjectedWalletAccounts$ = (\n\twallet: PolkadotInjectedWallet,\n): Observable<PolkadotAccount[]> => {\n\tconst injected = wallet.extension;\n\tif (!wallet.isConnected || !injected) return of([]);\n\n\treturn new Observable<PolkadotAccount[]>((subscriber) => {\n\t\tconst signPayload = injected.signer.signPayload.bind(injected.signer);\n\t\tconst signRaw = injected.signer.signRaw.bind(injected.signer);\n\t\tconst { field, factory } = getPjsSignerField();\n\n\t\tconst toAccount = (account: PolkadotInjectedAccount): PolkadotAccount => {\n\t\t\tconst { address } = account;\n\t\t\tconst type = account.type ?? \"sr25519\";\n\t\t\treturn {\n\t\t\t\t...account,\n\t\t\t\tid: getWalletAccountId(wallet.id, address),\n\t\t\t\ttype,\n\t\t\t\tplatform: \"polkadot\",\n\t\t\t\twalletName: wallet.name,\n\t\t\t\twalletId: wallet.id,\n\t\t\t\t[field]: factory(address, signPayload, signRaw, toSignerType(type)),\n\t\t\t\tsignRaw: async (data, options) =>\n\t\t\t\t\t(await signRaw({ address, ...encodeRawData(data, options?.type) }))\n\t\t\t\t\t\t.signature,\n\t\t\t} as Exclude<PolkadotAccount, { isPlaceholder: true }>;\n\t\t};\n\n\t\tconst toAccounts = (accounts: PolkadotInjectedAccount[]) =>\n\t\t\taccounts.flatMap((account) => {\n\t\t\t\ttry {\n\t\t\t\t\treturn [toAccount(account)];\n\t\t\t\t} catch {\n\t\t\t\t\treturn [];\n\t\t\t\t}\n\t\t\t});\n\n\t\tconst emit = (accounts: PolkadotInjectedAccount[]) => {\n\t\t\tlatestAccounts.set(injected, accounts);\n\t\t\tsubscriber.next(toAccounts(accounts));\n\t\t};\n\n\t\temit(latestAccounts.get(injected) ?? []);\n\t\treturn injected.accounts.subscribe(emit);\n\t});\n};\n\n/**\n * polkadot-api v2's `getPolkadotSignerFromPjs` takes three parameters and\n * ignores the fourth at runtime.\n */\ntype PjsSignerFactory = (\n\taddress: string,\n\tsignPayload: SignPayload,\n\tsignRaw: SignRaw,\n\ttype?: KeypairType,\n) => unknown;\n\ntype PjsSignerModule = {\n\tgetTxCreatorFromPjs?: PjsSignerFactory;\n\tgetPolkadotSignerFromPjs?: PjsSignerFactory;\n};\n\n/**\n * polkadot-api v3 replaced `polkadotSigner` (PolkadotSigner) with `txCreator`\n * (TxCreator). Which one the app's installed version provides is detected at\n * runtime so a single @kheopskit/core release supports both.\n */\nconst getPjsSignerField = (): {\n\tfield: \"txCreator\" | \"polkadotSigner\";\n\tfactory: PjsSignerFactory;\n} => {\n\tconst module = pjs as PjsSignerModule;\n\tif (module.getTxCreatorFromPjs)\n\t\treturn { field: \"txCreator\", factory: module.getTxCreatorFromPjs };\n\tif (module.getPolkadotSignerFromPjs)\n\t\treturn {\n\t\t\tfield: \"polkadotSigner\",\n\t\t\tfactory: module.getPolkadotSignerFromPjs,\n\t\t};\n\tthrow new KheopskitError(\n\t\t\"UNSUPPORTED_VERSION\",\n\t\t\"Unsupported polkadot-api/pjs-signer version\",\n\t);\n};\n\nconst requestSignMessage = (\n\tappKit: AppKitInstance,\n\tprovider: WalletConnectProvider,\n\taddress: string,\n\tmessage: string,\n) => {\n\tif (!provider.session)\n\t\tthrow new KheopskitError(\"NO_SESSION\", \"No session found\");\n\tconst chainId = appKit.getCaipNetworks(\"polkadot\")[0]?.caipNetworkId;\n\tif (!chainId)\n\t\tthrow new KheopskitError(\n\t\t\t\"NO_SESSION\",\n\t\t\t\"No CAIP network available for polkadot\",\n\t\t);\n\n\treturn provider.client.request<{ signature: RawSignature }>({\n\t\ttopic: provider.session.topic,\n\t\tchainId,\n\t\trequest: {\n\t\t\tmethod: \"polkadot_signMessage\",\n\t\t\tparams: { address, message },\n\t\t},\n\t});\n};\n\nconst getAppKitPolkadotSigning = (appKit: AppKitInstance, address: string) => {\n\tconst provider = appKit.getProvider(\"polkadot\");\n\tif (!provider) throw new KheopskitError(\"NO_PROVIDER\", \"No provider found\");\n\tif (!provider.session)\n\t\tthrow new KheopskitError(\"NO_SESSION\", \"No session found\");\n\n\tconst signMessage = (message: string) =>\n\t\trequestSignMessage(appKit, provider, address, message);\n\n\tconst { field, factory } = getPjsSignerField();\n\n\tconst signer = factory(\n\t\taddress,\n\t\t(transactionPayload) => {\n\t\t\tif (!provider.session)\n\t\t\t\tthrow new KheopskitError(\"NO_SESSION\", \"No session found\");\n\n\t\t\treturn provider.client.request({\n\t\t\t\ttopic: provider.session.topic,\n\t\t\t\tchainId: `polkadot:${transactionPayload.genesisHash.substring(2, 34)}`,\n\t\t\t\trequest: {\n\t\t\t\t\tmethod: \"polkadot_signTransaction\",\n\t\t\t\t\tparams: {\n\t\t\t\t\t\taddress,\n\t\t\t\t\t\ttransactionPayload,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t});\n\t\t},\n\t\tasync ({ data }) => ({\n\t\t\tid: 0,\n\t\t\tsignature: (await signMessage(data)).signature,\n\t\t}),\n\t\t\"sr25519\",\n\t);\n\n\tconst signRaw: PolkadotAccount[\"signRaw\"] = async (data) =>\n\t\t(await signMessage(encodeRawData(data).data)).signature;\n\n\treturn { [field]: signer, signRaw };\n};\n\nconst getWalletConnectAccounts$ = (\n\twallet: LiveWalletConnectWallet,\n): Observable<PolkadotAccount[]> =>\n\tgetWalletConnectSessionAccounts$({\n\t\twallet,\n\t\tplatform: \"polkadot\",\n\t\tnamespace: \"polkadot\",\n\t\tcacheKey: `accounts:${wallet.id}:polkadot:`,\n\t\tbuildAccounts: (provider) => {\n\t\t\tconst session = provider.session;\n\t\t\tif (!session) return [];\n\n\t\t\tconst addresses = getCaip10Addresses(\n\t\t\t\tgetSessionCaip10s(session, \"polkadot\"),\n\t\t\t);\n\n\t\t\treturn addresses.map(\n\t\t\t\t(address) =>\n\t\t\t\t\t({\n\t\t\t\t\t\tid: getWalletAccountId(wallet.id, address),\n\t\t\t\t\t\tplatform: \"polkadot\",\n\t\t\t\t\t\twalletName: wallet.name,\n\t\t\t\t\t\twalletId: wallet.id,\n\t\t\t\t\t\taddress,\n\t\t\t\t\t\t...getAppKitPolkadotSigning(wallet.appKit, address),\n\t\t\t\t\t\tgenesisHash: null,\n\t\t\t\t\t\tname: `${wallet.name} Polkadot`,\n\t\t\t\t\t\t// WalletConnect (Reown AppKit) doesn't expose account key type;\n\t\t\t\t\t\t// default to sr25519, which is the most common Polkadot key type.\n\t\t\t\t\t\ttype: \"sr25519\",\n\t\t\t\t\t}) as PolkadotAccount,\n\t\t\t);\n\t\t},\n\t});\n\nexport const getPolkadotAccounts$ = (\n\tpolkadotWallets$: Observable<(PolkadotWallet | WalletConnectWallet)[]>,\n\tpolkadotAccountTypes: PolkadotAccountType[],\n) => {\n\tif (polkadotAccountTypes.length === 0) {\n\t\tconsole.warn(\n\t\t\t\"[kheopskit] polkadot({ accountTypes }) is empty; all Polkadot accounts will be filtered out.\",\n\t\t);\n\t}\n\n\treturn createPlatformAccounts$({\n\t\twallets$: polkadotWallets$,\n\t\tgetInjectedAccounts$: getInjectedWalletAccounts$,\n\t\tgetWalletConnectAccounts$,\n\t\tmapAccounts: (accounts) =>\n\t\t\taccounts.filter((account) => polkadotAccountTypes.includes(account.type)),\n\t});\n};\n","import type {\n\tKheopskitPlatform,\n\tPlatformContext,\n\tPolkadotAccountType,\n} from \"../types\";\nimport { getPolkadotAccounts$ } from \"./accounts\";\nimport type { PolkadotAccount, PolkadotWallet } from \"./types\";\nimport { getPolkadotWallets$ } from \"./wallets\";\n\nconst DEFAULT_ACCOUNT_TYPES: PolkadotAccountType[] = [\n\t\"sr25519\",\n\t\"ed25519\",\n\t\"ecdsa\",\n];\n\nconst VALID_ACCOUNT_TYPES = new Set<string>([\n\t\"sr25519\",\n\t\"ed25519\",\n\t\"ecdsa\",\n\t\"ethereum\",\n]);\n\nexport type PolkadotPluginOptions = {\n\t/**\n\t * Allowed Polkadot account key types. Accounts with other key types are\n\t * filtered out from kheopskit state.\n\t *\n\t * @default [\"sr25519\", \"ed25519\", \"ecdsa\"]\n\t */\n\taccountTypes?: PolkadotAccountType[];\n};\n\n/**\n * Polkadot platform plugin. Pass to `createKheopskit({ platforms: [polkadot()] })`.\n *\n * @example\n * ```ts\n * import { polkadot } from \"@kheopskit/core/polkadot\";\n * polkadot({ accountTypes: [\"sr25519\", \"ed25519\", \"ecdsa\"] });\n * ```\n */\nexport const polkadot = (\n\toptions: PolkadotPluginOptions = {},\n): KheopskitPlatform<\"polkadot\", PolkadotWallet, PolkadotAccount> => {\n\tconst accountTypes = options.accountTypes ?? DEFAULT_ACCOUNT_TYPES;\n\n\tconst invalid = accountTypes.filter((t) => !VALID_ACCOUNT_TYPES.has(t));\n\tif (invalid.length > 0) {\n\t\tconsole.warn(\n\t\t\t`[kheopskit] Unknown polkadot accountTypes: ${JSON.stringify(invalid)}. Valid values: \"sr25519\", \"ed25519\", \"ecdsa\", \"ethereum\".`,\n\t\t);\n\t}\n\n\treturn {\n\t\tplatform: \"polkadot\",\n\t\tgetWallets$: (ctx: PlatformContext) =>\n\t\t\tgetPolkadotWallets$(ctx.store, ctx.config, ctx.registryReads$),\n\t\tgetAccounts$: (wallets$) => getPolkadotAccounts$(wallets$, accountTypes),\n\t\tacceptsCachedAccount: (cached) =>\n\t\t\taccountTypes.includes(cached.polkadotAccountType ?? \"sr25519\"),\n\t};\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmCA,MAAM,sBACL,aAEA,OAAO,UAAU,UAAU,QAAQ,cACnC,OAAO,SAAS,SAAS,cAAc,cACvC,OAAO,SAAS,QAAQ,gBAAgB,cACxC,OAAO,SAAS,OAAO,YAAY;;;;;;;AAQpC,MAAa,iCAAiB,IAAI,QAGhC;;;;;;;;AAaF,MAAM,kCAAkB,IAAI,QAG1B;AAEF,MAAM,kBAAkB,OACvB,YACA,OACA,YACI;CACJ,MAAM,WAAW,MAAM,MAAM,OAAO,OAAO;CAC3C,IAAI,CAAC,mBAAmB,QAAQ,GAC/B,MAAM,IAAI,MAAM,2BAA2B,WAAW,EAAE;CACzD,eAAe,IAAI,UAAU,MAAM,SAAS,SAAS,IAAI,CAAC;CAC1D,OAAO;AACR;AAEA,MAAM,oBACL,YACA,YAC+B;CAC/B,MAAM,QAAS,WAAkC,eAAe;CAChE,IAAI,CAAC,OACJ,OAAO,QAAQ,uBAAO,IAAI,MAAM,2BAA2B,WAAW,EAAE,CAAC;CAC1E,MAAM,UAAU,gBAAgB,IAAI,KAAK;CACzC,IAAI,SAAS,OAAO;CACpB,MAAM,aAAa,gBAAgB,YAAY,OAAO,OAAO;CAC7D,gBAAgB,IAAI,OAAO,UAAU;CACrC,MAAM,eAAe,gBAAgB,OAAO,KAAK;CACjD,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AAAA,mBACjBC,yBAAAA,kBAAkB,SAAS,UAAU,CAGvB,CAAC,CAAC,KACf,aACC;GACA,IAAIL,yBAAAA,mBAAmB,OAAO,IAAI,OAAO;GACzC,UAAU;GACV,YAAY,OAAO;GACnB,UAAU,OAAO;GACjB;GACA,GAAG,yBAAyB,OAAO,QAAQ,OAAO;GAClD,aAAa;GACb,MAAM,GAAG,OAAO,KAAK;GAGrB,MAAM;EACP,EACF;CACD;AACD,CAAC;AAEF,MAAa,wBACZ,kBACA,yBACI;CACJ,IAAI,qBAAqB,WAAW,GACnC,QAAQ,KACP,8FACD;CAGD,OAAOM,yBAAAA,wBAAwB;EAC9B,UAAU;EACV,sBAAsB;EACtB;EACA,cAAc,aACb,SAAS,QAAQ,YAAY,qBAAqB,SAAS,QAAQ,IAAI,CAAC;CAC1E,CAAC;AACF;;;ACrPA,MAAM,wBAA+C;CACpD;CACA;CACA;AACD;AAEA,MAAM,sCAAsB,IAAI,IAAY;CAC3C;CACA;CACA;CACA;AACD,CAAC;;;;;;;;;;AAqBD,MAAa,YACZ,UAAiC,CAAC,MACkC;CACpE,MAAM,eAAe,QAAQ,gBAAgB;CAE7C,MAAM,UAAU,aAAa,QAAQ,MAAM,CAAC,oBAAoB,IAAI,CAAC,CAAC;CACtE,IAAI,QAAQ,SAAS,GACpB,QAAQ,KACP,8CAA8C,KAAK,UAAU,OAAO,EAAE,2DACvE;CAGD,OAAO;EACN,UAAU;EACV,cAAc,QACb,oBAAoB,IAAI,OAAO,IAAI,QAAQ,IAAI,cAAc;EAC9D,eAAe,aAAa,qBAAqB,UAAU,YAAY;EACvE,uBAAuB,WACtB,aAAa,SAAS,OAAO,uBAAuB,SAAS;CAC/D;AACD"}
1
+ {"version":3,"file":"polkadot.js","names":["getInjectedExtensions","getWalletId","createRegistryReads$","createInjectedWallets$","map","distinctUntilChanged","isEqual","parseWalletId","isRefusalMessage","POLKADOT_EXTENSIONS","hex","of","Observable","getWalletAccountId","pjs","KheopskitError","getWalletConnectSessionAccounts$","getCaip10Addresses","getSessionCaip10s","createPlatformAccounts$"],"sources":["../src/api/polkadot/wallets.ts","../src/api/polkadot/accounts.ts","../src/api/polkadot/plugin.ts"],"sourcesContent":["import { isEqual } from \"lodash-es\";\nimport { getInjectedExtensions } from \"polkadot-api/pjs-signer\";\nimport { distinctUntilChanged, map, type Observable } from \"rxjs\";\nimport { POLKADOT_EXTENSIONS } from \"../../utils/polkadotExtensions\";\nimport { createRegistryReads$ } from \"../../utils/registryReads\";\nimport {\n\tgetWalletId,\n\tparseWalletId,\n\ttype WalletId,\n} from \"../../utils/WalletId\";\nimport { isRefusalMessage } from \"../errors\";\nimport { createInjectedWallets$ } from \"../injectedWallets\";\nimport type { KheopskitStore } from \"../store\";\nimport type { KheopskitConfig } from \"../types\";\nimport type {\n\tPolkadotInjected,\n\tPolkadotInjectedAccount,\n\tPolkadotInjectedWallet,\n} from \"./types\";\n\ntype EnableResult = {\n\taccounts?: Partial<PolkadotInjected[\"accounts\"]>;\n\tsigner?: Partial<PolkadotInjected[\"signer\"]>;\n\tmetadata?: unknown;\n\tprovider?: unknown;\n};\n\ntype InjectedWeb3Window = {\n\tinjectedWeb3?: Record<\n\t\tstring,\n\t\t| { enable(appName: string): Promise<EnableResult | null | undefined> }\n\t\t| undefined\n\t>;\n};\n\nconst isPolkadotInjected = (\n\tinjected: EnableResult | null | undefined,\n): injected is PolkadotInjected =>\n\ttypeof injected?.accounts?.get === \"function\" &&\n\ttypeof injected.accounts.subscribe === \"function\" &&\n\ttypeof injected.signer?.signPayload === \"function\" &&\n\ttypeof injected.signer.signRaw === \"function\";\n\n/**\n * The list each extension last reported: read when its connect was granted,\n * so the emission that first shows the wallet connected already lists it, and\n * updated by every `subscribe` callback, so an accounts stream that restarts\n * resumes from the current list rather than the connect-time one.\n */\nexport const latestAccounts = new WeakMap<\n\tPolkadotInjected,\n\tPolkadotInjectedAccount[]\n>();\n\ntype InjectedWeb3Entry = NonNullable<\n\tNonNullable<InjectedWeb3Window[\"injectedWeb3\"]>[string]\n>;\n\n/**\n * The connect each extension is still answering. An extension keeps its\n * prompt open after kheopskit abandons the attempt, and a second `enable()`\n * meanwhile fails (polkadot-js: \"Pending authorisation request already\n * exists\") or resolves unauthorised (Talisman), so a new attempt joins this\n * one instead.\n */\nconst pendingConnects = new WeakMap<\n\tInjectedWeb3Entry,\n\tPromise<PolkadotInjected>\n>();\n\nconst enableExtension = async (\n\tidentifier: string,\n\tentry: InjectedWeb3Entry,\n\tappName: string,\n) => {\n\tconst injected = await entry.enable(appName);\n\tif (!isPolkadotInjected(injected))\n\t\tthrow new Error(`Unsupported extension: \"${identifier}\"`);\n\tlatestAccounts.set(injected, await injected.accounts.get());\n\treturn injected;\n};\n\nconst connectExtension = (\n\tidentifier: string,\n\tappName: string,\n): Promise<PolkadotInjected> => {\n\tconst entry = (globalThis as InjectedWeb3Window).injectedWeb3?.[identifier];\n\tif (!entry)\n\t\treturn Promise.reject(new Error(`Unavailable extension: \"${identifier}\"`));\n\tconst pending = pendingConnects.get(entry);\n\tif (pending) return pending;\n\tconst connecting = enableExtension(identifier, entry, appName);\n\tpendingConnects.set(entry, connecting);\n\tconst settle = () => pendingConnects.delete(entry);\n\tconnecting.then(settle, settle);\n\treturn connecting;\n};\n\nconst getInjectedWalletsIds = () =>\n\ttypeof window === \"undefined\"\n\t\t? []\n\t\t: getInjectedExtensions().map((name) => getWalletId(\"polkadot\", name));\n\n// The shared WalletConnect connector is emitted once by core (see\n// `getWallets$`), not per platform — so this returns only injected wallets.\nexport const getPolkadotWallets$ = (\n\tstore: KheopskitStore,\n\tconfig: Pick<KheopskitConfig, \"appName\" | \"walletConnect\">,\n\tregistryReads$: Observable<void> = createRegistryReads$(),\n) =>\n\tcreateInjectedWallets$<WalletId, PolkadotInjectedWallet, PolkadotInjected>(\n\t\tstore,\n\t\t{\n\t\t\tsources$: registryReads$.pipe(\n\t\t\t\tmap(getInjectedWalletsIds),\n\t\t\t\tdistinctUntilChanged<WalletId[]>(isEqual),\n\t\t\t),\n\t\t\tgetWalletId: (walletId) => walletId,\n\t\t\tconnect: (walletId) =>\n\t\t\t\tconnectExtension(\n\t\t\t\t\tparseWalletId(walletId).identifier,\n\t\t\t\t\tconfig.appName ||\n\t\t\t\t\t\tconfig.walletConnect?.metadata.name ||\n\t\t\t\t\t\twindow.location.hostname,\n\t\t\t\t),\n\t\t\tisUserRejection: isRefusalMessage,\n\t\t\tbuildWallet: ({\n\t\t\t\twalletId,\n\t\t\t\thandle,\n\t\t\t\tstatus,\n\t\t\t\terror,\n\t\t\t\tisConnected,\n\t\t\t\tconnect,\n\t\t\t\tdisconnect,\n\t\t\t}) => {\n\t\t\t\tconst { identifier } = parseWalletId(walletId);\n\t\t\t\tconst extInfo = POLKADOT_EXTENSIONS[identifier];\n\n\t\t\t\treturn {\n\t\t\t\t\tid: walletId,\n\t\t\t\t\ttype: \"injected\",\n\t\t\t\t\tplatform: \"polkadot\",\n\t\t\t\t\tname: extInfo?.name ?? identifier,\n\t\t\t\t\ticon: extInfo?.icon ?? \"\",\n\t\t\t\t\tsourceId: identifier,\n\t\t\t\t\textension: handle,\n\t\t\t\t\tstatus,\n\t\t\t\t\terror,\n\t\t\t\t\tisConnected,\n\t\t\t\t\tconnect,\n\t\t\t\t\tdisconnect,\n\t\t\t\t};\n\t\t\t},\n\t\t},\n\t);\n","import { hex } from \"@scure/base\";\nimport type {\n\tKeypairType,\n\tSignPayload,\n\tSignRaw,\n} from \"polkadot-api/pjs-signer\";\nimport * as pjs from \"polkadot-api/pjs-signer\";\nimport { Observable, of } from \"rxjs\";\nimport { getWalletAccountId } from \"../../utils\";\nimport { KheopskitError } from \"../errors\";\nimport {\n\tcreatePlatformAccounts$,\n\tgetCaip10Addresses,\n\tgetSessionCaip10s,\n\tgetWalletConnectSessionAccounts$,\n\ttype LiveWalletConnectWallet,\n} from \"../platformAccounts\";\nimport type {\n\tAppKitInstance,\n\tPolkadotAccountType,\n\tWalletConnectProvider,\n\tWalletConnectWallet,\n} from \"../types\";\nimport type {\n\tPolkadotAccount,\n\tPolkadotInjected,\n\tPolkadotInjectedAccount,\n\tPolkadotInjectedWallet,\n\tPolkadotSignRawType,\n\tPolkadotWallet,\n} from \"./types\";\nimport { latestAccounts } from \"./wallets\";\n\ntype RawSignature = `0x${string}`;\n\nconst encodeRawData = (\n\tdata: string | Uint8Array,\n\ttype?: PolkadotSignRawType,\n): { data: string; type: PolkadotSignRawType } =>\n\ttypeof data === \"string\"\n\t\t? { data, type: type ?? \"payload\" }\n\t\t: { data: `0x${hex.encode(data)}`, type: type ?? \"bytes\" };\n\n/**\n * pjs-signer's signature-type map knows ed25519, sr25519 and ecdsa only, so an\n * `ethereum` type would get a 64-byte mock signature where ecdsa needs 65.\n */\nconst toSignerType = (type: PolkadotAccountType): KeypairType =>\n\ttype === \"ethereum\" ? \"ecdsa\" : type;\n\nconst getInjectedWalletAccounts$ = (\n\twallet: PolkadotInjectedWallet,\n): Observable<PolkadotAccount[]> => {\n\tconst injected = wallet.extension;\n\tif (!wallet.isConnected || !injected) return of([]);\n\n\treturn new Observable<PolkadotAccount[]>((subscriber) => {\n\t\tconst signPayload = injected.signer.signPayload.bind(injected.signer);\n\t\tconst signRaw = injected.signer.signRaw.bind(injected.signer);\n\t\tconst createTransaction = injected.signer.createTransaction?.bind(\n\t\t\tinjected.signer,\n\t\t);\n\t\tconst { field, factory, getAccountTxCreator } = getPjsSignerField();\n\t\tconst createSigner = (address: string, type: KeypairType) =>\n\t\t\tcreateTransaction && getAccountTxCreator\n\t\t\t\t? getAccountTxCreator(address, createTransaction, signRaw, type)\n\t\t\t\t: factory(address, signPayload, signRaw, type);\n\n\t\tconst toAccount = (account: PolkadotInjectedAccount): PolkadotAccount => {\n\t\t\tconst { address } = account;\n\t\t\tconst type = account.type ?? \"sr25519\";\n\t\t\treturn {\n\t\t\t\t...account,\n\t\t\t\tid: getWalletAccountId(wallet.id, address),\n\t\t\t\ttype,\n\t\t\t\tplatform: \"polkadot\",\n\t\t\t\twalletName: wallet.name,\n\t\t\t\twalletId: wallet.id,\n\t\t\t\t[field]: createSigner(address, toSignerType(type)),\n\t\t\t\tsignRaw: async (data, options) =>\n\t\t\t\t\t(await signRaw({ address, ...encodeRawData(data, options?.type) }))\n\t\t\t\t\t\t.signature,\n\t\t\t} as Exclude<PolkadotAccount, { isPlaceholder: true }>;\n\t\t};\n\n\t\tconst toAccounts = (accounts: PolkadotInjectedAccount[]) =>\n\t\t\taccounts.flatMap((account) => {\n\t\t\t\ttry {\n\t\t\t\t\treturn [toAccount(account)];\n\t\t\t\t} catch {\n\t\t\t\t\treturn [];\n\t\t\t\t}\n\t\t\t});\n\n\t\tconst emit = (accounts: PolkadotInjectedAccount[]) => {\n\t\t\tlatestAccounts.set(injected, accounts);\n\t\t\tsubscriber.next(toAccounts(accounts));\n\t\t};\n\n\t\temit(latestAccounts.get(injected) ?? []);\n\t\treturn injected.accounts.subscribe(emit);\n\t});\n};\n\n/**\n * polkadot-api v2's `getPolkadotSignerFromPjs` takes three parameters and\n * ignores the fourth at runtime.\n */\ntype PjsSignerFactory = (\n\taddress: string,\n\tsignPayload: SignPayload,\n\tsignRaw: SignRaw,\n\ttype?: KeypairType,\n) => unknown;\n\ntype PjsSignerModule = {\n\tgetTxCreatorFromPjs?: PjsSignerFactory;\n\tgetPolkadotSignerFromPjs?: PjsSignerFactory;\n\tgetAccountTxCreator?: (\n\t\taddress: string,\n\t\tcreateTransaction: NonNullable<\n\t\t\tPolkadotInjected[\"signer\"][\"createTransaction\"]\n\t\t>,\n\t\tsignRaw: SignRaw,\n\t\ttype: KeypairType,\n\t) => unknown;\n};\n\n/**\n * polkadot-api v3 replaced `polkadotSigner` (PolkadotSigner) with `txCreator`\n * (TxCreator). Which one the app's installed version provides is detected at\n * runtime so a single @kheopskit/core release supports both. Newer v3 releases\n * add `getAccountTxCreator`, which lets the wallet build the transaction.\n */\nconst getPjsSignerField = (): {\n\tfield: \"txCreator\" | \"polkadotSigner\";\n\tfactory: PjsSignerFactory;\n\tgetAccountTxCreator?: PjsSignerModule[\"getAccountTxCreator\"];\n} => {\n\tconst module = pjs as PjsSignerModule;\n\tif (module.getTxCreatorFromPjs)\n\t\treturn {\n\t\t\tfield: \"txCreator\",\n\t\t\tfactory: module.getTxCreatorFromPjs,\n\t\t\tgetAccountTxCreator: module.getAccountTxCreator,\n\t\t};\n\tif (module.getPolkadotSignerFromPjs)\n\t\treturn {\n\t\t\tfield: \"polkadotSigner\",\n\t\t\tfactory: module.getPolkadotSignerFromPjs,\n\t\t};\n\tthrow new KheopskitError(\n\t\t\"UNSUPPORTED_VERSION\",\n\t\t\"Unsupported polkadot-api/pjs-signer version\",\n\t);\n};\n\nconst requestSignMessage = (\n\tappKit: AppKitInstance,\n\tprovider: WalletConnectProvider,\n\taddress: string,\n\tmessage: string,\n) => {\n\tif (!provider.session)\n\t\tthrow new KheopskitError(\"NO_SESSION\", \"No session found\");\n\tconst chainId = appKit.getCaipNetworks(\"polkadot\")[0]?.caipNetworkId;\n\tif (!chainId)\n\t\tthrow new KheopskitError(\n\t\t\t\"NO_SESSION\",\n\t\t\t\"No CAIP network available for polkadot\",\n\t\t);\n\n\treturn provider.client.request<{ signature: RawSignature }>({\n\t\ttopic: provider.session.topic,\n\t\tchainId,\n\t\trequest: {\n\t\t\tmethod: \"polkadot_signMessage\",\n\t\t\tparams: { address, message },\n\t\t},\n\t});\n};\n\nconst getAppKitPolkadotSigning = (appKit: AppKitInstance, address: string) => {\n\tconst provider = appKit.getProvider(\"polkadot\");\n\tif (!provider) throw new KheopskitError(\"NO_PROVIDER\", \"No provider found\");\n\tif (!provider.session)\n\t\tthrow new KheopskitError(\"NO_SESSION\", \"No session found\");\n\n\tconst signMessage = (message: string) =>\n\t\trequestSignMessage(appKit, provider, address, message);\n\n\tconst { field, factory } = getPjsSignerField();\n\n\tconst signer = factory(\n\t\taddress,\n\t\t(transactionPayload) => {\n\t\t\tif (!provider.session)\n\t\t\t\tthrow new KheopskitError(\"NO_SESSION\", \"No session found\");\n\n\t\t\treturn provider.client.request({\n\t\t\t\ttopic: provider.session.topic,\n\t\t\t\tchainId: `polkadot:${transactionPayload.genesisHash.substring(2, 34)}`,\n\t\t\t\trequest: {\n\t\t\t\t\tmethod: \"polkadot_signTransaction\",\n\t\t\t\t\tparams: {\n\t\t\t\t\t\taddress,\n\t\t\t\t\t\ttransactionPayload,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t});\n\t\t},\n\t\tasync ({ data }) => ({\n\t\t\tid: 0,\n\t\t\tsignature: (await signMessage(data)).signature,\n\t\t}),\n\t\t\"sr25519\",\n\t);\n\n\tconst signRaw: PolkadotAccount[\"signRaw\"] = async (data) =>\n\t\t(await signMessage(encodeRawData(data).data)).signature;\n\n\treturn { [field]: signer, signRaw };\n};\n\nconst getWalletConnectAccounts$ = (\n\twallet: LiveWalletConnectWallet,\n): Observable<PolkadotAccount[]> =>\n\tgetWalletConnectSessionAccounts$({\n\t\twallet,\n\t\tplatform: \"polkadot\",\n\t\tnamespace: \"polkadot\",\n\t\tcacheKey: `accounts:${wallet.id}:polkadot:`,\n\t\tbuildAccounts: (provider) => {\n\t\t\tconst session = provider.session;\n\t\t\tif (!session) return [];\n\n\t\t\tconst addresses = getCaip10Addresses(\n\t\t\t\tgetSessionCaip10s(session, \"polkadot\"),\n\t\t\t);\n\n\t\t\treturn addresses.map(\n\t\t\t\t(address) =>\n\t\t\t\t\t({\n\t\t\t\t\t\tid: getWalletAccountId(wallet.id, address),\n\t\t\t\t\t\tplatform: \"polkadot\",\n\t\t\t\t\t\twalletName: wallet.name,\n\t\t\t\t\t\twalletId: wallet.id,\n\t\t\t\t\t\taddress,\n\t\t\t\t\t\t...getAppKitPolkadotSigning(wallet.appKit, address),\n\t\t\t\t\t\tgenesisHash: null,\n\t\t\t\t\t\tname: `${wallet.name} Polkadot`,\n\t\t\t\t\t\t// WalletConnect (Reown AppKit) doesn't expose account key type;\n\t\t\t\t\t\t// default to sr25519, which is the most common Polkadot key type.\n\t\t\t\t\t\ttype: \"sr25519\",\n\t\t\t\t\t}) as PolkadotAccount,\n\t\t\t);\n\t\t},\n\t});\n\nexport const getPolkadotAccounts$ = (\n\tpolkadotWallets$: Observable<(PolkadotWallet | WalletConnectWallet)[]>,\n\tpolkadotAccountTypes: PolkadotAccountType[],\n) => {\n\tif (polkadotAccountTypes.length === 0) {\n\t\tconsole.warn(\n\t\t\t\"[kheopskit] polkadot({ accountTypes }) is empty; all Polkadot accounts will be filtered out.\",\n\t\t);\n\t}\n\n\treturn createPlatformAccounts$({\n\t\twallets$: polkadotWallets$,\n\t\tgetInjectedAccounts$: getInjectedWalletAccounts$,\n\t\tgetWalletConnectAccounts$,\n\t\tmapAccounts: (accounts) =>\n\t\t\taccounts.filter((account) => polkadotAccountTypes.includes(account.type)),\n\t});\n};\n","import type {\n\tKheopskitPlatform,\n\tPlatformContext,\n\tPolkadotAccountType,\n} from \"../types\";\nimport { getPolkadotAccounts$ } from \"./accounts\";\nimport type { PolkadotAccount, PolkadotWallet } from \"./types\";\nimport { getPolkadotWallets$ } from \"./wallets\";\n\nconst DEFAULT_ACCOUNT_TYPES: PolkadotAccountType[] = [\n\t\"sr25519\",\n\t\"ed25519\",\n\t\"ecdsa\",\n];\n\nconst VALID_ACCOUNT_TYPES = new Set<string>([\n\t\"sr25519\",\n\t\"ed25519\",\n\t\"ecdsa\",\n\t\"ethereum\",\n]);\n\nexport type PolkadotPluginOptions = {\n\t/**\n\t * Allowed Polkadot account key types. Accounts with other key types are\n\t * filtered out from kheopskit state.\n\t *\n\t * @default [\"sr25519\", \"ed25519\", \"ecdsa\"]\n\t */\n\taccountTypes?: PolkadotAccountType[];\n};\n\n/**\n * Polkadot platform plugin. Pass to `createKheopskit({ platforms: [polkadot()] })`.\n *\n * @example\n * ```ts\n * import { polkadot } from \"@kheopskit/core/polkadot\";\n * polkadot({ accountTypes: [\"sr25519\", \"ed25519\", \"ecdsa\"] });\n * ```\n */\nexport const polkadot = (\n\toptions: PolkadotPluginOptions = {},\n): KheopskitPlatform<\"polkadot\", PolkadotWallet, PolkadotAccount> => {\n\tconst accountTypes = options.accountTypes ?? DEFAULT_ACCOUNT_TYPES;\n\n\tconst invalid = accountTypes.filter((t) => !VALID_ACCOUNT_TYPES.has(t));\n\tif (invalid.length > 0) {\n\t\tconsole.warn(\n\t\t\t`[kheopskit] Unknown polkadot accountTypes: ${JSON.stringify(invalid)}. Valid values: \"sr25519\", \"ed25519\", \"ecdsa\", \"ethereum\".`,\n\t\t);\n\t}\n\n\treturn {\n\t\tplatform: \"polkadot\",\n\t\tgetWallets$: (ctx: PlatformContext) =>\n\t\t\tgetPolkadotWallets$(ctx.store, ctx.config, ctx.registryReads$),\n\t\tgetAccounts$: (wallets$) => getPolkadotAccounts$(wallets$, accountTypes),\n\t\tacceptsCachedAccount: (cached) =>\n\t\t\taccountTypes.includes(cached.polkadotAccountType ?? \"sr25519\"),\n\t};\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmCA,MAAM,sBACL,aAEA,OAAO,UAAU,UAAU,QAAQ,cACnC,OAAO,SAAS,SAAS,cAAc,cACvC,OAAO,SAAS,QAAQ,gBAAgB,cACxC,OAAO,SAAS,OAAO,YAAY;;;;;;;AAQpC,MAAa,iCAAiB,IAAI,QAGhC;;;;;;;;AAaF,MAAM,kCAAkB,IAAI,QAG1B;AAEF,MAAM,kBAAkB,OACvB,YACA,OACA,YACI;CACJ,MAAM,WAAW,MAAM,MAAM,OAAO,OAAO;CAC3C,IAAI,CAAC,mBAAmB,QAAQ,GAC/B,MAAM,IAAI,MAAM,2BAA2B,WAAW,EAAE;CACzD,eAAe,IAAI,UAAU,MAAM,SAAS,SAAS,IAAI,CAAC;CAC1D,OAAO;AACR;AAEA,MAAM,oBACL,YACA,YAC+B;CAC/B,MAAM,QAAS,WAAkC,eAAe;CAChE,IAAI,CAAC,OACJ,OAAO,QAAQ,uBAAO,IAAI,MAAM,2BAA2B,WAAW,EAAE,CAAC;CAC1E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