import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest' // Create a mock TON provider that satisfies the InjectedWalletApi interface const createMockTonProvider = (name = 'Trust Wallet') => ({ deviceInfo: { platform: 'chrome', appName: name, appVersion: '1.0.0', maxProtocolVersion: 2, features: [] }, walletInfo: { name, app_name: name.toLowerCase().replace(/\s/g, ''), image: 'https://example.com/icon.png', about_url: 'https://example.com', tondns: '', platforms: ['chrome'], features: [] }, protocolVersion: 2, isWalletBrowser: false, connect: vi.fn(), restoreConnection: vi.fn(), send: vi.fn(), listen: vi.fn(() => vi.fn()), disconnect: vi.fn() }) // Create a mock parentAPI that simulates what Comlink.wrap returns const createMockParentAPI = ( opts: { eip6963Ready?: boolean walletStandardReady?: boolean bip122Ready?: boolean tronReady?: boolean tonReady?: boolean eip6963Wallets?: any[] walletStandardWallets?: any[] bip122Wallets?: any[] tronWallets?: any[] tonWallets?: any[] parentOrigin?: string } = {} ) => ({ eip6963WalletsReady: opts.eip6963Ready ?? true, walletStandardWalletsReady: opts.walletStandardReady ?? true, bip122WalletsReady: opts.bip122Ready ?? true, tronWalletsReady: opts.tronReady ?? true, tonWalletsReady: opts.tonReady ?? true, eip6963Wallets: opts.eip6963Wallets ?? [], walletStandardWallets: opts.walletStandardWallets ?? [], bip122Wallets: opts.bip122Wallets ?? [], tronWallets: opts.tronWallets ?? [], tonWallets: opts.tonWallets ?? [], parentOrigin: opts.parentOrigin ?? 'https://parent.example.com', discoverTronWallets: vi.fn(), discoverTonWallets: vi.fn() }) let mockWrappedAPI: ReturnType | null = null // Mock Comlink vi.mock('comlink', () => ({ wrap: vi.fn(() => mockWrappedAPI), windowEndpoint: vi.fn().mockReturnValue({}), proxy: vi.fn((obj: unknown) => obj) })) // Store original window properties const originalParent = window.parent const originalReferrer = Object.getOwnPropertyDescriptor(document, 'referrer') describe('BridgeChild', () => { beforeEach(() => { vi.clearAllMocks() vi.useFakeTimers() vi.resetModules() // Reset window globals delete (window as any).UWCBridgeChildInitialized delete (window as any).eip6963Wallets delete (window as any).walletStandardWallets delete (window as any).walletStandardBitcoinWallets delete (window as any).tronWallets delete (window as any).tonWallets delete (window as any).uwcParentOrigin delete (window as any).trustwalletTon delete (window as any).tonkeeper delete (window as any).okxTonWallet Reflect.deleteProperty(window, '__uwcRefreshBip122Accounts') mockWrappedAPI = createMockParentAPI() // Mock document.referrer Object.defineProperty(document, 'referrer', { value: 'https://parent.example.com/page', writable: true, configurable: true }) }) afterEach(() => { vi.useRealTimers() vi.restoreAllMocks() // Cleanup window globals delete (window as any).UWCBridgeChildInitialized delete (window as any).eip6963Wallets delete (window as any).walletStandardWallets delete (window as any).walletStandardBitcoinWallets delete (window as any).tronWallets delete (window as any).tonWallets delete (window as any).uwcParentOrigin delete (window as any).trustwalletTon delete (window as any).tonkeeper delete (window as any).okxTonWallet Reflect.deleteProperty(window, '__uwcRefreshBip122Accounts') // Restore document.referrer if (originalReferrer) { Object.defineProperty(document, 'referrer', originalReferrer) } }) // Helper to create a BridgeChild by simulating iframe context const createBridgeChildInIframe = async (options?: { tronInjectedIds?: string[] tonJsBridgeKeys?: string[] onError?: (info: { namespace: string; message: string }) => void }) => { // Mock window.parent to be different from window (iframe context) Object.defineProperty(window, 'parent', { value: { postMessage: vi.fn() }, writable: true, configurable: true }) const { BridgeChild } = await import('./BridgeChild') const child = new BridgeChild(options) // Restore parent after construction Object.defineProperty(window, 'parent', { value: originalParent, writable: true, configurable: true }) return child } describe('constructor', () => { it('should accept empty options', async () => { const child = await createBridgeChildInIframe() expect(child).toBeDefined() }) it('should accept tronInjectedIds option', async () => { const child = await createBridgeChildInIframe({ tronInjectedIds: ['tronLink'] }) expect(child).toBeDefined() }) }) describe('initializeConnection', () => { it('should not initialize when window.parent equals window (not in iframe)', async () => { const Comlink = await import('comlink') // window.parent === window means we're NOT in an iframe Object.defineProperty(window, 'parent', { value: window, writable: true, configurable: true }) const { BridgeChild } = await import('./BridgeChild') new BridgeChild() await vi.advanceTimersByTimeAsync(200) expect(Comlink.wrap).not.toHaveBeenCalled() expect((window as any).UWCBridgeChildInitialized).toBeUndefined() Object.defineProperty(window, 'parent', { value: originalParent, writable: true, configurable: true }) }) it('should set UWCBridgeChildInitialized when in iframe', async () => { await createBridgeChildInIframe() expect((window as any).UWCBridgeChildInitialized).toBe(true) }) it('should call Comlink.wrap and windowEndpoint', async () => { const Comlink = await import('comlink') await createBridgeChildInIframe() expect(Comlink.windowEndpoint).toHaveBeenCalled() expect(Comlink.wrap).toHaveBeenCalled() }) }) describe('wallet polling', () => { it('should set EIP6963 wallets on window when parent is ready', async () => { const mockEip6963 = [ { uuid: 'wallet-1', name: 'MetaMask', icon: 'mm-icon', rdns: 'io.metamask', provider: { request: vi.fn() } } ] mockWrappedAPI = createMockParentAPI({ eip6963Wallets: mockEip6963 }) await createBridgeChildInIframe() // Allow poll cycle to complete await vi.advanceTimersByTimeAsync(500) expect((window as any).eip6963Wallets).toBeDefined() expect((window as any).eip6963Wallets).toHaveLength(1) expect((window as any).eip6963Wallets[0].uuid).toBe('wallet-1') }) it('should set Wallet Standard wallets on window', async () => { const mockSolana = [ { uuid: 'phantom-solana', name: 'Phantom', chains: ['solana:mainnet'], features: ['standard:connect'], adapter: {} } ] mockWrappedAPI = createMockParentAPI({ walletStandardWallets: mockSolana }) await createBridgeChildInIframe() await vi.advanceTimersByTimeAsync(500) expect((window as any).walletStandardWallets).toBeDefined() expect((window as any).walletStandardWallets).toHaveLength(1) expect((window as any).walletStandardWallets[0].name).toBe('Phantom') }) it('should set Bitcoin wallets on window', async () => { const mockBitcoin = [ { uuid: 'metamask-bitcoin', name: 'MetaMask', features: ['bitcoin:connect'], wallet: { name: 'MetaMask', accounts: [], features: {} } } ] mockWrappedAPI = createMockParentAPI({ bip122Wallets: mockBitcoin }) await createBridgeChildInIframe() await vi.advanceTimersByTimeAsync(500) expect((window as any).walletStandardBitcoinWallets).toBeDefined() expect((window as any).walletStandardBitcoinWallets).toHaveLength(1) expect((window as any).walletStandardBitcoinWallets[0].name).toBe( 'MetaMask' ) expect((window as any).walletStandardBitcoinWallets[0].wallet.name).toBe( 'MetaMask' ) }) it('should set Tron wallets on window', async () => { const mockTron = [ { uuid: 'tron-tronlink', name: 'tronLink', injectedId: 'tronLink', provider: { tronWeb: {} } } ] mockWrappedAPI = createMockParentAPI({ tronWallets: mockTron }) await createBridgeChildInIframe({ tronInjectedIds: ['tronLink'] }) await vi.advanceTimersByTimeAsync(500) expect((window as any).tronWallets).toBeDefined() expect((window as any).tronWallets).toHaveLength(1) expect((window as any).tronWallets[0].uuid).toBe('tron-tronlink') }) it('should call discoverTronWallets with provided injectedIds', async () => { mockWrappedAPI = createMockParentAPI() await createBridgeChildInIframe({ tronInjectedIds: ['tronLink', 'tokenpocket.tron'] }) await vi.advanceTimersByTimeAsync(500) expect(mockWrappedAPI!.discoverTronWallets).toHaveBeenCalledWith([ 'tronLink', 'tokenpocket.tron' ]) }) it('should continue polling when wallets are not ready', async () => { mockWrappedAPI = createMockParentAPI({ eip6963Ready: false, walletStandardReady: false, tronReady: false }) await createBridgeChildInIframe() await vi.advanceTimersByTimeAsync(500) // Window globals should NOT be set when not ready expect((window as any).eip6963Wallets).toBeUndefined() }) it('should stop polling when wallets are already set on window', async () => { // Pre-set wallets on window ;(window as any).eip6963Wallets = [{ uuid: 'existing' }] mockWrappedAPI = createMockParentAPI() await createBridgeChildInIframe() await vi.advanceTimersByTimeAsync(500) // discoverTronWallets should not be called since polling stopped early expect(mockWrappedAPI!.discoverTronWallets).not.toHaveBeenCalled() }) it('should handle errors gracefully and continue polling', async () => { // First call throws, subsequent calls succeed let callCount = 0 const failingAPI = { get eip6963WalletsReady() { callCount++ if (callCount <= 1) { throw new Error('API not ready') } return true }, walletStandardWalletsReady: true, tronWalletsReady: true, eip6963Wallets: [], walletStandardWallets: [], tronWallets: [], discoverTronWallets: vi.fn() } mockWrappedAPI = failingAPI as any await createBridgeChildInIframe() await vi.advanceTimersByTimeAsync(1000) // Should eventually succeed and set wallets expect((window as any).eip6963Wallets).toBeDefined() }) }) describe('Tron/TON discovery race (premature empty default)', () => { it('does not default Tron to [] while a triggered discovery is still pending, then delivers the wallet once ready', async () => { const mockTron = [ { uuid: 'tron-tronlink', name: 'tronLink', injectedId: 'tronLink', provider: { tronWeb: {} } } ] // Parent supports Tron but reports not-ready at first (e.g. TronLink's // tronWeb hasn't finished injecting yet). EVM + Solana resolve instantly. let tronReady = false const api = { eip6963WalletsReady: true, walletStandardWalletsReady: true, tonWalletsReady: true, eip6963Wallets: [], walletStandardWallets: [], tonWallets: [], tronWallets: mockTron, get tronWalletsReady() { return tronReady }, discoverTronWallets: vi.fn(), discoverTonWallets: vi.fn() } mockWrappedAPI = api as any await createBridgeChildInIframe({ tronInjectedIds: ['tronLink'] }) // EVM + Solana resolve and several poll ticks pass while Tron is pending. await vi.advanceTimersByTimeAsync(200) // The placeholder must NOT default Tron to `[]` here: the injected // connector's pollForBridgeTronWallets resolves on the first array it // sees, so a premature `[]` makes it report "none found" and miss the // real wallet marshalled below. expect((window as any).tronWallets).toBeUndefined() // Parent finishes Tron discovery (tronWeb now injected). tronReady = true await vi.advanceTimersByTimeAsync(100) expect((window as any).tronWallets).toHaveLength(1) expect((window as any).tronWallets[0].uuid).toBe('tron-tronlink') }) it('does not default TON to [] while a triggered discovery is still pending, then delivers the wallet once ready', async () => { const mockTon = [ { uuid: 'ton-trustwalletto', name: 'Trust Wallet', icon: '', jsBridgeKey: 'trustwalletTon', provider: createMockTonProvider('Trust Wallet') } ] let tonReady = false const api = { eip6963WalletsReady: true, walletStandardWalletsReady: true, tronWalletsReady: true, eip6963Wallets: [], walletStandardWallets: [], tronWallets: [], tonWallets: mockTon, get tonWalletsReady() { return tonReady }, discoverTronWallets: vi.fn(), discoverTonWallets: vi.fn() } mockWrappedAPI = api as any await createBridgeChildInIframe({ tonJsBridgeKeys: ['trustwalletTon'] }) await vi.advanceTimersByTimeAsync(200) // Same race as Tron: the placeholder must not pre-empt a pending TON // discovery, or the connector's poll resolves empty and misses it. expect((window as any).tonWallets).toBeUndefined() tonReady = true await vi.advanceTimersByTimeAsync(100) expect((window as any).tonWallets).toHaveLength(1) expect((window as any).tonWallets[0].uuid).toBe('ton-trustwalletto') }) it('still backstops Tron to [] at MAX_POLL_MS when the parent never reports ready', async () => { const api = { eip6963WalletsReady: true, walletStandardWalletsReady: true, tonWalletsReady: true, eip6963Wallets: [], walletStandardWallets: [], tonWallets: [], tronWallets: [], tronWalletsReady: false, discoverTronWallets: vi.fn(), discoverTonWallets: vi.fn() } mockWrappedAPI = api as any await createBridgeChildInIframe({ tronInjectedIds: ['tronLink'] }) // Pending → not prematurely defaulted. await vi.advanceTimersByTimeAsync(500) expect((window as any).tronWallets).toBeUndefined() // Past MAX_POLL_MS (5s) the fillEmptyDefaults backstop resolves it to []. await vi.advanceTimersByTimeAsync(5000) expect((window as any).tronWallets).toEqual([]) }) it('recovers Tron when the parent exposes late (Comlink reads hang until then)', async () => { // Reproduces the iframe-example race: BridgeParent is created on the // iframe `load` event, so its Comlink endpoint isn't live when the child // starts polling. A Comlink read to a not-yet-exposed parent never settles // (comlink.ts requestResponseMessage has no timeout) — simulate with a // getter returning a never-settling promise until the parent goes "live". const mockTron = [ { uuid: 'tron-tronlink', name: 'tronLink', injectedId: 'tronLink', provider: { tronWeb: {} } } ] let live = false const hang = () => new Promise(() => {}) const api = { get eip6963WalletsReady() { return live ? true : hang() }, get walletStandardWalletsReady() { return live ? true : hang() }, get tronWalletsReady() { return live ? true : hang() }, get tonWalletsReady() { return live ? true : hang() }, eip6963Wallets: [], walletStandardWallets: [], tronWallets: mockTron, tonWallets: [], discoverTronWallets: vi.fn(), discoverTonWallets: vi.fn() } mockWrappedAPI = api as any await createBridgeChildInIframe({ tronInjectedIds: ['tronLink'] }) // Parent not live yet: reads time out and the loop retries — it must NOT // hang (the bug). Tron stays undiscovered for now. await vi.advanceTimersByTimeAsync(600) expect((window as any).tronWallets).toBeUndefined() // Parent's BridgeParent finally exposes — the child must recover. live = true await vi.advanceTimersByTimeAsync(600) expect((window as any).tronWallets).toHaveLength(1) expect((window as any).tronWallets[0].uuid).toBe('tron-tronlink') }) it('recovers EIP-6963 when the parent exposes late (same raceParentRead path as Tron)', async () => { // EVM/Solana use the same per-tick raceParentRead recovery as Tron, so a // late-exposing parent must not strand them either. const mockEip = [ { uuid: 'mm', name: 'MetaMask', icon: '', rdns: 'io.metamask', provider: { request: vi.fn() } } ] let live = false const hang = () => new Promise(() => {}) const api = { get eip6963WalletsReady() { return live ? true : hang() }, get walletStandardWalletsReady() { return live ? true : hang() }, get tronWalletsReady() { return live ? true : hang() }, get tonWalletsReady() { return live ? true : hang() }, eip6963Wallets: mockEip, walletStandardWallets: [], tronWallets: [], tonWallets: [], discoverTronWallets: vi.fn(), discoverTonWallets: vi.fn() } mockWrappedAPI = api as any await createBridgeChildInIframe() // Pre-expose: reads time out, the loop retries, nothing set yet. await vi.advanceTimersByTimeAsync(600) expect((window as any).eip6963Wallets).toBeUndefined() // Parent exposes — the child must recover EVM, not just Tron. live = true await vi.advanceTimersByTimeAsync(600) expect((window as any).eip6963Wallets).toHaveLength(1) expect((window as any).eip6963Wallets[0].uuid).toBe('mm') }) it('recovers TON when the parent exposes late (same raceParentRead path as Tron)', async () => { const mockTon = [ { uuid: 'ton-tonkeeper', name: 'Tonkeeper', icon: '', jsBridgeKey: 'tonkeeper', provider: createMockTonProvider('Tonkeeper') } ] let live = false const hang = () => new Promise(() => {}) const api = { get eip6963WalletsReady() { return live ? true : hang() }, get walletStandardWalletsReady() { return live ? true : hang() }, get tronWalletsReady() { return live ? true : hang() }, get tonWalletsReady() { return live ? true : hang() }, eip6963Wallets: [], walletStandardWallets: [], tronWallets: [], tonWallets: mockTon, discoverTronWallets: vi.fn(), discoverTonWallets: vi.fn() } mockWrappedAPI = api as any await createBridgeChildInIframe({ tonJsBridgeKeys: ['tonkeeper'] }) await vi.advanceTimersByTimeAsync(600) expect((window as any).tonWallets).toBeUndefined() live = true await vi.advanceTimersByTimeAsync(600) expect((window as any).tonWallets).toHaveLength(1) expect((window as any).tonWallets[0].uuid).toBe('ton-tonkeeper') }) it('recovers Solana when the parent exposes late (same raceParentRead path as Tron)', async () => { const mockSolana = [ { uuid: 'phantom-solana', name: 'Phantom', chains: ['solana:mainnet'], features: ['standard:connect'], adapter: {} } ] let live = false const hang = () => new Promise(() => {}) const api = { get eip6963WalletsReady() { return live ? true : hang() }, get walletStandardWalletsReady() { return live ? true : hang() }, get tronWalletsReady() { return live ? true : hang() }, get tonWalletsReady() { return live ? true : hang() }, eip6963Wallets: [], walletStandardWallets: mockSolana, tronWallets: [], tonWallets: [], discoverTronWallets: vi.fn(), discoverTonWallets: vi.fn() } mockWrappedAPI = api as any await createBridgeChildInIframe() await vi.advanceTimersByTimeAsync(600) expect((window as any).walletStandardWallets).toBeUndefined() live = true await vi.advanceTimersByTimeAsync(600) expect((window as any).walletStandardWallets).toHaveLength(1) expect((window as any).walletStandardWallets[0].name).toBe('Phantom') }) it('recovers Bitcoin when the parent exposes late (same raceParentRead path as Tron)', async () => { const mockBitcoin = [ { uuid: 'metamask-bitcoin', name: 'MetaMask', features: ['bitcoin:connect'], wallet: { name: 'MetaMask', accounts: [], features: {} } } ] let live = false const hang = () => new Promise(() => {}) const api = { get eip6963WalletsReady() { return live ? true : hang() }, get walletStandardWalletsReady() { return live ? true : hang() }, get bip122WalletsReady() { return live ? true : hang() }, get tronWalletsReady() { return live ? true : hang() }, get tonWalletsReady() { return live ? true : hang() }, eip6963Wallets: [], walletStandardWallets: [], bip122Wallets: mockBitcoin, tronWallets: [], tonWallets: [], discoverTronWallets: vi.fn(), discoverTonWallets: vi.fn() } mockWrappedAPI = api as any await createBridgeChildInIframe() // Pre-expose: reads time out, the loop retries, nothing set yet. await vi.advanceTimersByTimeAsync(600) expect((window as any).walletStandardBitcoinWallets).toBeUndefined() // Parent exposes — the child must recover Bitcoin, not just Tron. live = true await vi.advanceTimersByTimeAsync(600) expect((window as any).walletStandardBitcoinWallets).toHaveLength(1) expect((window as any).walletStandardBitcoinWallets[0].name).toBe( 'MetaMask' ) }) }) describe('backward compatibility with older BridgeParent (no Tron)', () => { it('should still set EVM and Solana wallets when parent has no Tron support', async () => { const eip6963Wallets = [ { uuid: 'mm-1', name: 'MetaMask', icon: 'mm-icon', rdns: 'io.metamask', provider: { request: vi.fn() } } ] const walletStandardWallets = [ { uuid: 'phantom-1', name: 'Phantom', chains: ['solana:mainnet'], features: ['standard:connect'], adapter: {} } ] // Defensive path: a parent whose Tron property access THROWS (e.g. a // non-Comlink stub). Real old Comlink parents instead resolve a missing // prop to undefined — see the fail-fast test below. Both end at // tronWallets = []. const oldParentAPI = { eip6963WalletsReady: true, walletStandardWalletsReady: true, eip6963Wallets, walletStandardWallets, get tronWalletsReady(): boolean { throw new Error('tronWalletsReady is not defined') }, get tronWallets(): unknown[] { throw new Error('tronWallets is not defined') }, get discoverTronWallets() { return undefined } } mockWrappedAPI = oldParentAPI as any await createBridgeChildInIframe({ tronInjectedIds: ['tronLink'] }) await vi.advanceTimersByTimeAsync(500) // EVM and Solana should still be set expect((window as any).eip6963Wallets).toHaveLength(1) expect((window as any).eip6963Wallets[0].uuid).toBe('mm-1') expect((window as any).walletStandardWallets).toHaveLength(1) expect((window as any).walletStandardWallets[0].name).toBe('Phantom') // Tron should fall back to empty array expect((window as any).tronWallets).toEqual([]) }) it('fail-fasts Tron and TON to [] on a real old parent (missing props resolve to undefined, not throw)', async () => { // Real Comlink resolves a GET on a missing property to `undefined` (only // an APPLY on a missing method rejects) — and a resolved read proves the // parent is LIVE (a pre-expose read hangs into BridgeReadTimeout instead), // so `undefined` is a definitive "namespace not supported", never a // pending state. The child must complete those namespaces immediately: // retrying to the MAX_POLL_MS backstop stalled consumer-side wallet // detection ~5 s on every embed hosted by an old SDK (mesh-web-sdk 3.3.x // ships uwc-bridge-parent 0.0.2, which predates tron/ton). const onError = vi.fn() const oldParentAPI = { eip6963WalletsReady: true, walletStandardWalletsReady: true, eip6963Wallets: [], walletStandardWallets: [], parentOrigin: 'https://parent.example.com' // No tronWalletsReady / tonWalletsReady / discover* — a Comlink GET on // a missing prop would resolve them to undefined. } mockWrappedAPI = oldParentAPI as any await createBridgeChildInIframe({ tronInjectedIds: ['tronLink'], onError }) // Completed well before MAX_POLL_MS — a couple of ticks, not 5 s. await vi.advanceTimersByTimeAsync(200) expect((window as any).tronWallets).toEqual([]) expect((window as any).tonWallets).toEqual([]) // EVM / Solana still marshalled from the live parent. expect((window as any).eip6963Wallets).toEqual([]) expect((window as any).walletStandardWallets).toEqual([]) // Observability: reported once per unsupported namespace (deduped). // bip122 is also missing on this old parent, so it fail-fasts too. const namespaces = onError.mock.calls .map(([info]) => info.namespace) .sort() expect(namespaces).toEqual(['bip122', 'tron', 'tvm']) }) it('fail-fasts Bitcoin to [] immediately on a real old parent (missing bip122 props resolve to undefined, not throw)', async () => { // An older BridgeParent predates Bitcoin bridge support entirely — no // bip122Wallets/bip122WalletsReady at all. A Comlink GET on a missing // property resolves to undefined (not a throw), so this must not crash // the child; a resolved-`undefined` readiness means "live parent without // this namespace", so it completes with [] IMMEDIATELY (like every other // namespace) rather than stalling to the MAX_POLL_MS backstop. const onError = vi.fn() const oldParentAPI = { eip6963WalletsReady: true, walletStandardWalletsReady: true, eip6963Wallets: [], walletStandardWallets: [], tronWalletsReady: true, tronWallets: [], tonWalletsReady: true, tonWallets: [], parentOrigin: 'https://parent.example.com' // No bip122Wallets / bip122WalletsReady — resolve to undefined. } mockWrappedAPI = oldParentAPI as any await createBridgeChildInIframe({ onError }) // Completed well before MAX_POLL_MS — a couple of ticks, not 5 s. await vi.advanceTimersByTimeAsync(200) expect((window as any).walletStandardBitcoinWallets).toEqual([]) // Reported once as an unsupported namespace. const namespaces = onError.mock.calls.map(([info]) => info.namespace) expect(namespaces).toContain('bip122') }) it('should set tron to empty array when discoverTronWallets throws', async () => { const apiWithBrokenDiscover = { eip6963WalletsReady: true, walletStandardWalletsReady: true, eip6963Wallets: [], walletStandardWallets: [], tronWalletsReady: true, tronWallets: [], discoverTronWallets: vi.fn(() => { throw new Error('Method not supported') }) } mockWrappedAPI = apiWithBrokenDiscover as any await createBridgeChildInIframe({ tronInjectedIds: ['tronLink'] }) await vi.advanceTimersByTimeAsync(500) expect((window as any).eip6963Wallets).toEqual([]) expect((window as any).walletStandardWallets).toEqual([]) expect((window as any).tronWallets).toEqual([]) }) it('should not block on tron when tronWalletsReady is false', async () => { const eip6963Wallets = [ { uuid: 'mm-1', name: 'MetaMask', icon: 'mm-icon', rdns: 'io.metamask', provider: { request: vi.fn() } } ] mockWrappedAPI = createMockParentAPI({ eip6963Wallets, tronReady: false, tronWallets: [] }) await createBridgeChildInIframe() await vi.advanceTimersByTimeAsync(500) // EVM and Solana should be set even though tron is not ready expect((window as any).eip6963Wallets).toHaveLength(1) expect((window as any).walletStandardWallets).toEqual([]) // Tron stays undefined while the parent reports not-ready — we must NOT // prematurely default it to []. The connector's poll resolves on the first // array it sees, so an early [] makes it miss a wallet that arrives a // moment later. tryMarshalTron writes it once the parent reports ready, or // the MAX_POLL_MS backstop fills [] if it never does. expect((window as any).tronWallets).toBeUndefined() }) it('calls discoverTronWallets once when Tron resolves on the first tick (re-issues per tick until tronDone otherwise)', async () => { // Not a general invariant: the design re-issues discovery every tick until // tronDone. Here Tron is ready immediately, so it marshals and sets // tronDone on tick 1 — hence exactly one call. A slow parent would see one // call per tick until ready. let callCount = 0 const progressiveAPI = { get eip6963WalletsReady() { callCount++ return callCount > 1 }, walletStandardWalletsReady: true, tronWalletsReady: true, eip6963Wallets: [], walletStandardWallets: [], tronWallets: [], discoverTronWallets: vi.fn() } mockWrappedAPI = progressiveAPI as any await createBridgeChildInIframe({ tronInjectedIds: ['tronLink'] }) await vi.advanceTimersByTimeAsync(1000) // Tron reports ready on the first tick, so tryMarshalTron marshals and // sets tronDone — it stops re-issuing discoverTronWallets after that. expect(progressiveAPI.discoverTronWallets).toHaveBeenCalledTimes(1) }) }) describe('TON Connect window shim (iframe bridge)', () => { it('should inject window[jsBridgeKey].tonconnect adapter for each bridged TON wallet', async () => { const mockProvider = createMockTonProvider('Trust Wallet') const tonWallets = [ { uuid: 'ton-trustwalletto', name: 'Trust Wallet', icon: '', jsBridgeKey: 'trustwalletTon', provider: mockProvider } ] mockWrappedAPI = createMockParentAPI({ tonWallets, tonReady: true }) await createBridgeChildInIframe({ tonJsBridgeKeys: ['trustwalletTon'] }) await vi.advanceTimersByTimeAsync(500) // The SDK's isWindowContainsWallet check const shimRoot = (window as any).trustwalletTon expect(shimRoot).toBeDefined() expect(typeof shimRoot).toBe('object') expect('tonconnect' in shimRoot).toBe(true) // Adapter should have static properties as plain values (not Promises) const tc = shimRoot.tonconnect expect(tc.deviceInfo.appName).toBe('Trust Wallet') expect(tc.walletInfo.name).toBe('Trust Wallet') expect(tc.walletInfo.app_name).toBe('trustwallet') expect(tc.protocolVersion).toBe(2) expect(tc.isWalletBrowser).toBe(false) // Methods should be functions expect(typeof tc.connect).toBe('function') expect(typeof tc.send).toBe('function') expect(typeof tc.listen).toBe('function') expect(typeof tc.disconnect).toBe('function') expect(typeof tc.restoreConnection).toBe('function') }) it('should inject adapters for multiple TON wallets', async () => { const trustProvider = createMockTonProvider('Trust Wallet') const tonkeeperProvider = createMockTonProvider('Tonkeeper') const tonWallets = [ { uuid: 'ton-trustwalletto', name: 'Trust Wallet', icon: '', jsBridgeKey: 'trustwalletTon', provider: trustProvider }, { uuid: 'ton-tonkeeper', name: 'Tonkeeper', icon: '', jsBridgeKey: 'tonkeeper', provider: tonkeeperProvider } ] mockWrappedAPI = createMockParentAPI({ tonWallets, tonReady: true }) await createBridgeChildInIframe({ tonJsBridgeKeys: ['trustwalletTon', 'tonkeeper'] }) await vi.advanceTimersByTimeAsync(500) expect( (window as any).trustwalletTon?.tonconnect?.deviceInfo?.appName ).toBe('Trust Wallet') expect((window as any).tonkeeper?.tonconnect?.deviceInfo?.appName).toBe( 'Tonkeeper' ) }) it('should forward connect calls through the proxy', async () => { const mockProvider = createMockTonProvider('Trust Wallet') mockProvider.connect.mockResolvedValue({ event: 'connect', payload: {} }) const tonWallets = [ { uuid: 'ton-tw', name: 'Trust Wallet', icon: '', jsBridgeKey: 'trustwalletTon', provider: mockProvider } ] mockWrappedAPI = createMockParentAPI({ tonWallets, tonReady: true }) await createBridgeChildInIframe({ tonJsBridgeKeys: ['trustwalletTon'] }) await vi.advanceTimersByTimeAsync(500) const tc = (window as any).trustwalletTon.tonconnect await tc.connect(2, { manifestUrl: 'https://example.com' }) expect(mockProvider.connect).toHaveBeenCalledWith(2, { manifestUrl: 'https://example.com' }) }) it('should return a sync unsubscribe function from listen', async () => { const mockUnsub = vi.fn() const mockProvider = createMockTonProvider('Trust Wallet') mockProvider.listen.mockReturnValue(mockUnsub) const tonWallets = [ { uuid: 'ton-tw', name: 'Trust Wallet', icon: '', jsBridgeKey: 'trustwalletTon', provider: mockProvider } ] mockWrappedAPI = createMockParentAPI({ tonWallets, tonReady: true }) await createBridgeChildInIframe({ tonJsBridgeKeys: ['trustwalletTon'] }) await vi.advanceTimersByTimeAsync(500) const tc = (window as any).trustwalletTon.tonconnect const unsub = tc.listen(() => {}) // Should return a function synchronously expect(typeof unsub).toBe('function') }) it('should not inject shim when wallet has no jsBridgeKey', async () => { const tonWallets = [ { uuid: 'ton-unknown', name: 'Unknown', icon: '', jsBridgeKey: '', provider: createMockTonProvider() } ] mockWrappedAPI = createMockParentAPI({ tonWallets, tonReady: true }) await createBridgeChildInIframe({ tonJsBridgeKeys: [''] }) await vi.advanceTimersByTimeAsync(500) expect((window as any)['']).toBeUndefined() }) it('should not inject shim when wallet has no provider', async () => { const tonWallets = [ { uuid: 'ton-trustwalletto', name: 'Trust Wallet', icon: '', jsBridgeKey: 'trustwalletTon', provider: undefined } ] mockWrappedAPI = createMockParentAPI({ tonWallets, tonReady: true }) await createBridgeChildInIframe({ tonJsBridgeKeys: ['trustwalletTon'] }) await vi.advanceTimersByTimeAsync(500) expect((window as any).trustwalletTon).toBeUndefined() }) it('should not inject any shims when no TON wallets are discovered', async () => { mockWrappedAPI = createMockParentAPI({ tonWallets: [], tonReady: true }) await createBridgeChildInIframe({ tonJsBridgeKeys: ['trustwalletTon'] }) await vi.advanceTimersByTimeAsync(500) expect((window as any).trustwalletTon).toBeUndefined() }) it('should set window.uwcParentOrigin from bridge', async () => { mockWrappedAPI = createMockParentAPI({ parentOrigin: 'https://stake.com' }) await createBridgeChildInIframe() await vi.advanceTimersByTimeAsync(500) expect((window as any).uwcParentOrigin).toBe('https://stake.com') }) it('preserves a real in-frame TON provider instead of overwriting it with the bridge shim', async () => { // The extension has already injected its real provider into THIS frame. const nativeProvider = createMockTonProvider('Tonkeeper') const nativeRoot = { tonconnect: nativeProvider } ;(window as any).tonkeeper = nativeRoot // The bridge also reports the same wallet from the parent. const tonWallets = [ { uuid: 'ton-tonkeeper', name: 'Tonkeeper', icon: '', jsBridgeKey: 'tonkeeper', provider: createMockTonProvider('Tonkeeper') } ] mockWrappedAPI = createMockParentAPI({ tonWallets, tonReady: true }) await createBridgeChildInIframe({ tonJsBridgeKeys: ['tonkeeper'] }) await vi.advanceTimersByTimeAsync(500) // window.tonkeeper must remain the extension's real provider, untouched — // so the SDK binds to it and connect() attributes to the iframe origin. expect((window as any).tonkeeper).toBe(nativeRoot) expect((window as any).tonkeeper.tonconnect).toBe(nativeProvider) }) it('still injects the parent-forwarding shim when this frame has no native provider (mobile in-wallet browser)', async () => { // No window.tonkeeper in this frame — the provider lives in the top frame. const parentProvider = createMockTonProvider('Tonkeeper') const tonWallets = [ { uuid: 'ton-tonkeeper', name: 'Tonkeeper', icon: '', jsBridgeKey: 'tonkeeper', provider: parentProvider } ] mockWrappedAPI = createMockParentAPI({ tonWallets, tonReady: true }) await createBridgeChildInIframe({ tonJsBridgeKeys: ['tonkeeper'] }) await vi.advanceTimersByTimeAsync(500) // The shim is installed and forwards connect() to the parent proxy. const tc = (window as any).tonkeeper?.tonconnect expect(tc).toBeDefined() expect(typeof tc.connect).toBe('function') await tc.connect(2, { manifestUrl: 'https://example.com' }) expect(parentProvider.connect).toHaveBeenCalledWith(2, { manifestUrl: 'https://example.com' }) }) it('recovers parentOrigin when the parent exposes late (same raceParentRead path as wallets)', async () => { // syncParentOrigin shares the late-expose hazard: a parentOrigin read posted // before the parent's Comlink.expose never settles. The retry loop must keep // trying until the parent comes up, then set window.uwcParentOrigin. let live = false const hang = () => new Promise(() => {}) const api = { eip6963WalletsReady: true, walletStandardWalletsReady: true, tronWalletsReady: true, tonWalletsReady: true, eip6963Wallets: [], walletStandardWallets: [], tronWallets: [], tonWallets: [], get parentOrigin() { return live ? 'https://stake.com' : hang() }, discoverTronWallets: vi.fn(), discoverTonWallets: vi.fn() } mockWrappedAPI = api as any await createBridgeChildInIframe() // Parent not live yet: the read times out and the loop retries — it must // NOT hang and must NOT set a value. await vi.advanceTimersByTimeAsync(600) expect((window as any).uwcParentOrigin).toBeUndefined() // Parent's BridgeParent finally exposes — the retry must recover. live = true await vi.advanceTimersByTimeAsync(600) expect((window as any).uwcParentOrigin).toBe('https://stake.com') }) }) describe('bridge provider-event subscription globals', () => { it('installs window.__uwcSubscribeEip6963ProviderEvent that forwards to parentAPI', async () => { mockWrappedAPI = createMockParentAPI() const teardownFn = vi.fn() ;(mockWrappedAPI as any).subscribeEip6963ProviderEvent = vi .fn() .mockResolvedValue(teardownFn) await createBridgeChildInIframe({}) await vi.advanceTimersByTimeAsync(500) expect(typeof (window as any).__uwcSubscribeEip6963ProviderEvent).toBe( 'function' ) const callback = vi.fn() const unsubscribe = (window as any).__uwcSubscribeEip6963ProviderEvent( 'uuid-1', 'accountsChanged', callback ) expect(typeof unsubscribe).toBe('function') expect( (mockWrappedAPI as any).subscribeEip6963ProviderEvent ).toHaveBeenCalledWith('uuid-1', 'accountsChanged', callback, undefined) await Promise.resolve() unsubscribe() expect(teardownFn).toHaveBeenCalled() }) it('forwards the optional rdns argument to parentAPI.subscribeEip6963ProviderEvent', async () => { mockWrappedAPI = createMockParentAPI() const teardownFn = vi.fn() ;(mockWrappedAPI as any).subscribeEip6963ProviderEvent = vi .fn() .mockResolvedValue(teardownFn) await createBridgeChildInIframe({}) await vi.advanceTimersByTimeAsync(500) const callback = vi.fn() ;(window as any).__uwcSubscribeEip6963ProviderEvent( 'uuid-1', 'accountsChanged', callback, 'io.metamask' ) expect( (mockWrappedAPI as any).subscribeEip6963ProviderEvent ).toHaveBeenCalledWith( 'uuid-1', 'accountsChanged', callback, 'io.metamask' ) }) it('unsubscribing before the parentAPI round-trip resolves still tears down once it does', async () => { mockWrappedAPI = createMockParentAPI() const teardownFn = vi.fn() let resolveSubscribe!: (value: unknown) => void ;(mockWrappedAPI as any).subscribeEip6963ProviderEvent = vi .fn() .mockReturnValue( new Promise(resolve => { resolveSubscribe = resolve }) ) await createBridgeChildInIframe({}) await vi.advanceTimersByTimeAsync(500) const unsubscribe = (window as any).__uwcSubscribeEip6963ProviderEvent( 'uuid-1', 'accountsChanged', vi.fn() ) // Caller tears down BEFORE the parent responds. unsubscribe() resolveSubscribe(teardownFn) await Promise.resolve() expect(teardownFn).toHaveBeenCalled() }) it('installs window.__uwcSubscribeTronProviderEvent that forwards to parentAPI', async () => { mockWrappedAPI = createMockParentAPI() const teardownFn = vi.fn() ;(mockWrappedAPI as any).subscribeTronProviderEvent = vi .fn() .mockResolvedValue(teardownFn) await createBridgeChildInIframe({}) await vi.advanceTimersByTimeAsync(500) expect(typeof (window as any).__uwcSubscribeTronProviderEvent).toBe( 'function' ) const callback = vi.fn() ;(window as any).__uwcSubscribeTronProviderEvent( 'tronLink', 'accountsChanged', callback ) expect( (mockWrappedAPI as any).subscribeTronProviderEvent ).toHaveBeenCalledWith('tronLink', 'accountsChanged', callback) }) it('installs window.__uwcSubscribeSolanaWalletEvent that forwards to parentAPI', async () => { mockWrappedAPI = createMockParentAPI() const teardownFn = vi.fn() ;(mockWrappedAPI as any).subscribeSolanaWalletEvent = vi .fn() .mockResolvedValue(teardownFn) await createBridgeChildInIframe({}) await vi.advanceTimersByTimeAsync(500) expect(typeof (window as any).__uwcSubscribeSolanaWalletEvent).toBe( 'function' ) const callback = vi.fn() const unsubscribe = (window as any).__uwcSubscribeSolanaWalletEvent( 'phantom-solana:mainnet', callback ) expect(typeof unsubscribe).toBe('function') expect( (mockWrappedAPI as any).subscribeSolanaWalletEvent ).toHaveBeenCalledWith('phantom-solana:mainnet', callback) await Promise.resolve() unsubscribe() expect(teardownFn).toHaveBeenCalled() }) it('unsubscribing __uwcSubscribeSolanaWalletEvent before the parentAPI round-trip resolves still tears down once it does', async () => { mockWrappedAPI = createMockParentAPI() const teardownFn = vi.fn() let resolveSubscribe!: (value: unknown) => void ;(mockWrappedAPI as any).subscribeSolanaWalletEvent = vi .fn() .mockReturnValue( new Promise(resolve => { resolveSubscribe = resolve }) ) await createBridgeChildInIframe({}) await vi.advanceTimersByTimeAsync(500) const unsubscribe = (window as any).__uwcSubscribeSolanaWalletEvent( 'phantom-solana:mainnet', vi.fn() ) // Caller tears down BEFORE the parent responds — the race guard. unsubscribe() resolveSubscribe(teardownFn) await Promise.resolve() expect(teardownFn).toHaveBeenCalled() }) it('reports a bridge error when parentAPI.subscribeSolanaWalletEvent rejects (walletId not found)', async () => { mockWrappedAPI = createMockParentAPI() ;(mockWrappedAPI as any).subscribeSolanaWalletEvent = vi .fn() .mockRejectedValue( new Error( 'subscribeSolanaWalletEvent: no wallet found for walletId "x"' ) ) const errors: Array<{ namespace: string; message: string }> = [] await createBridgeChildInIframe({ onError: e => errors.push(e) }) await vi.advanceTimersByTimeAsync(500) ;(window as any).__uwcSubscribeSolanaWalletEvent('x', vi.fn()) await Promise.resolve() await Promise.resolve() expect(errors).toEqual([ { namespace: 'solana', message: 'subscribeSolanaWalletEvent: no wallet found for walletId "x"' } ]) }) it('installs window.__uwcSubscribeBip122WalletEvent that forwards to parentAPI', async () => { mockWrappedAPI = createMockParentAPI() const teardownFn = vi.fn() ;(mockWrappedAPI as any).subscribeBip122WalletEvent = vi .fn() .mockResolvedValue(teardownFn) await createBridgeChildInIframe({}) await vi.advanceTimersByTimeAsync(500) expect(typeof (window as any).__uwcSubscribeBip122WalletEvent).toBe( 'function' ) const callback = vi.fn() const unsubscribe = (window as any).__uwcSubscribeBip122WalletEvent( 'metamask-bitcoin:mainnet', callback ) expect(typeof unsubscribe).toBe('function') expect( (mockWrappedAPI as any).subscribeBip122WalletEvent ).toHaveBeenCalledWith('metamask-bitcoin:mainnet', callback) await Promise.resolve() unsubscribe() expect(teardownFn).toHaveBeenCalled() }) it('unsubscribing __uwcSubscribeBip122WalletEvent before the parentAPI round-trip resolves still tears down once it does', async () => { mockWrappedAPI = createMockParentAPI() const teardownFn = vi.fn() let resolveSubscribe!: (value: unknown) => void ;(mockWrappedAPI as any).subscribeBip122WalletEvent = vi .fn() .mockReturnValue( new Promise(resolve => { resolveSubscribe = resolve }) ) await createBridgeChildInIframe({}) await vi.advanceTimersByTimeAsync(500) const unsubscribe = (window as any).__uwcSubscribeBip122WalletEvent( 'metamask-bitcoin:mainnet', vi.fn() ) // Caller tears down BEFORE the parent responds — the race guard. unsubscribe() resolveSubscribe(teardownFn) await Promise.resolve() expect(teardownFn).toHaveBeenCalled() }) it('reports a bridge error when parentAPI.subscribeBip122WalletEvent rejects (walletId not found)', async () => { mockWrappedAPI = createMockParentAPI() ;(mockWrappedAPI as any).subscribeBip122WalletEvent = vi .fn() .mockRejectedValue( new Error( 'subscribeBip122WalletEvent: no wallet found for walletId "x"' ) ) const errors: Array<{ namespace: string; message: string }> = [] await createBridgeChildInIframe({ onError: e => errors.push(e) }) await vi.advanceTimersByTimeAsync(500) ;(window as any).__uwcSubscribeBip122WalletEvent('x', vi.fn()) await Promise.resolve() await Promise.resolve() expect(errors).toEqual([ { namespace: 'bip122', message: 'subscribeBip122WalletEvent: no wallet found for walletId "x"' } ]) }) describe('__uwcRefreshBip122Accounts', () => { const WALLET_ID = 'metamask-bitcoin:mainnet' const ADDRESS = 'bc1qjxztncefrl5czfyfxd449t8tht634g9cnaz5ka' // What crosses the bridge (BridgeParent's Bip122WireAccount) and what // the child rebuilds from it. type WireAccount = { address: string publicKey: number[] purpose?: string } type LocalWallet = { uuid: string wallet: { accounts: { address: string; publicKey: Uint8Array }[] } } type BridgedWindow = Window & { walletStandardBitcoinWallets?: LocalWallet[] __uwcRefreshBip122Accounts?: (walletId: string) => Promise } const bridgedWindow = window as BridgedWindow // The parent's entry for one bip122 wallet, granted nothing yet. const parentEntry = (uuid = WALLET_ID) => ({ uuid, name: 'MetaMask', features: ['bitcoin:connect'], wallet: { name: 'MetaMask', accounts: [] as WireAccount[], features: {} } }) const localWallet = (uuid = WALLET_ID): LocalWallet => { const local = bridgedWindow.walletStandardBitcoinWallets?.find( wallet => wallet.uuid === uuid ) if (!local) throw new Error(`BridgeChild marshaled no ${uuid}`) return local } const marshal = async ( entry: ReturnType, onError?: (info: { namespace: string; message: string }) => void ) => { mockWrappedAPI = createMockParentAPI({ bip122Wallets: [entry] }) await createBridgeChildInIframe({ onError }) await vi.advanceTimersByTimeAsync(500) const local = localWallet() expect(local.wallet.accounts).toEqual([]) return local } const refresh = async (walletId: string): Promise => { const hook = bridgedWindow.__uwcRefreshBip122Accounts if (!hook) throw new Error('BridgeChild did not install the hook') await hook(walletId) } it('re-reads the accounts from the parent into the marshaled wallet, in place', async () => { const entry = parentEntry() const local = await marshal(entry) // A connect on another namespace granted the Bitcoin account after // the bridge started. entry.wallet.accounts = [ { address: ADDRESS, publicKey: [3, 65, 234], purpose: 'payment' } ] await refresh(WALLET_ID) // Same object the injected connector already holds. expect(localWallet()).toBe(local) expect(local.wallet.accounts).toEqual([ { address: ADDRESS, publicKey: Uint8Array.from([3, 65, 234]), purpose: 'payment' } ]) }) it('picks up a revoke too', async () => { const entry = parentEntry() entry.wallet.accounts = [{ address: ADDRESS, publicKey: [3] }] mockWrappedAPI = createMockParentAPI({ bip122Wallets: [entry] }) await createBridgeChildInIframe() await vi.advanceTimersByTimeAsync(500) const local = localWallet() expect(local.wallet.accounts).toHaveLength(1) entry.wallet.accounts = [] await refresh(WALLET_ID) expect(local.wallet.accounts).toEqual([]) }) it('refreshes each wallet from its own parent entry, leaving the others alone', async () => { const OTHER_ID = 'other-wallet-bitcoin:mainnet' const OTHER_ADDRESS = 'bc1qotherwallet' const first = parentEntry() const second = parentEntry(OTHER_ID) mockWrappedAPI = createMockParentAPI({ bip122Wallets: [first, second] }) await createBridgeChildInIframe() await vi.advanceTimersByTimeAsync(500) const localFirst = localWallet() const localSecond = localWallet(OTHER_ID) // Both granted in the parent; only the second is refreshed. first.wallet.accounts = [{ address: ADDRESS, publicKey: [3] }] second.wallet.accounts = [{ address: OTHER_ADDRESS, publicKey: [2] }] await refresh(OTHER_ID) expect(localSecond.wallet.accounts).toEqual([ { address: OTHER_ADDRESS, publicKey: Uint8Array.from([2]) } ]) expect(localFirst.wallet.accounts).toEqual([]) }) it('refreshes the first of two wallets sharing a uuid from its own parent entry', async () => { const first = parentEntry() const second = parentEntry() mockWrappedAPI = createMockParentAPI({ bip122Wallets: [first, second] }) await createBridgeChildInIframe() await vi.advanceTimersByTimeAsync(500) const local = localWallet() second.wallet.accounts = [{ address: ADDRESS, publicKey: [3] }] await refresh(WALLET_ID) expect(local.wallet.accounts).toEqual([]) }) it('leaves the copy alone for a wallet it never marshaled', async () => { const entry = parentEntry() const local = await marshal(entry) entry.wallet.accounts = [{ address: ADDRESS, publicKey: [3] }] await refresh('some-other-wallet') expect(local.wallet.accounts).toEqual([]) }) it('never copies accounts from another wallet now at the same parent index', async () => { const entry = parentEntry() const local = await marshal(entry) entry.uuid = 'other-wallet-bitcoin:mainnet' entry.wallet.accounts = [{ address: ADDRESS, publicKey: [3] }] await refresh(WALLET_ID) expect(local.wallet.accounts).toEqual([]) }) it('keeps the copy, without reporting, when the parent has no account list', async () => { const entry = parentEntry() entry.wallet.accounts = [{ address: ADDRESS, publicKey: [3] }] mockWrappedAPI = createMockParentAPI({ bip122Wallets: [entry] }) const errors: Array<{ namespace: string; message: string }> = [] await createBridgeChildInIframe({ onError: e => errors.push(e) }) await vi.advanceTimersByTimeAsync(500) const local = localWallet() Object.defineProperty(entry.wallet, 'accounts', { value: undefined }) await refresh(WALLET_ID) expect(local.wallet.accounts).toHaveLength(1) expect(errors).toEqual([]) }) it('keeps the copy and reports the error when the parent read fails', async () => { const entry = parentEntry() const errors: Array<{ namespace: string; message: string }> = [] const local = await marshal(entry, e => errors.push(e)) Object.defineProperty(entry.wallet, 'accounts', { get() { throw new Error('parent read failed') } }) await refresh(WALLET_ID) expect(local.wallet.accounts).toEqual([]) expect(errors).toEqual([ { namespace: 'bip122', message: 'parent read failed' } ]) }) it('keeps the copy, without reporting, when the parent does not answer in time', async () => { const entry = parentEntry() const errors: Array<{ namespace: string; message: string }> = [] const local = await marshal(entry, e => errors.push(e)) Object.defineProperty(entry.wallet, 'accounts', { get: () => new Promise(() => {}) }) const pending = refresh(WALLET_ID) await vi.advanceTimersByTimeAsync(200) await pending expect(local.wallet.accounts).toEqual([]) expect(errors).toEqual([]) }) }) it('reports a bridge error when parentAPI.subscribeEip6963ProviderEvent rejects (uuid not found)', async () => { mockWrappedAPI = createMockParentAPI() ;(mockWrappedAPI as any).subscribeEip6963ProviderEvent = vi .fn() .mockRejectedValue( new Error( 'subscribeEip6963ProviderEvent: no wallet found for uuid "x"' ) ) const errors: Array<{ namespace: string; message: string }> = [] await createBridgeChildInIframe({ onError: e => errors.push(e) }) await vi.advanceTimersByTimeAsync(500) ;(window as any).__uwcSubscribeEip6963ProviderEvent( 'x', 'accountsChanged', vi.fn() ) await Promise.resolve() await Promise.resolve() expect(errors).toEqual([ { namespace: 'eip155', message: 'subscribeEip6963ProviderEvent: no wallet found for uuid "x"' } ]) }) it('reports a bridge error when parentAPI.subscribeTronProviderEvent rejects (no provider at path)', async () => { mockWrappedAPI = createMockParentAPI() ;(mockWrappedAPI as any).subscribeTronProviderEvent = vi .fn() .mockRejectedValue( new Error( 'subscribeTronProviderEvent: no provider found at injectedId "window.x"' ) ) const errors: Array<{ namespace: string; message: string }> = [] await createBridgeChildInIframe({ onError: e => errors.push(e) }) await vi.advanceTimersByTimeAsync(500) ;(window as any).__uwcSubscribeTronProviderEvent( 'window.x', 'accountsChanged', vi.fn() ) await Promise.resolve() await Promise.resolve() expect(errors).toEqual([ { namespace: 'tron', message: 'subscribeTronProviderEvent: no provider found at injectedId "window.x"' } ]) }) }) describe('checkWallets with all wallet types', () => { it('should fetch all wallet types and set on window', async () => { const eip6963Wallets = [ { uuid: 'mm-1', name: 'MetaMask', icon: 'mm-icon', rdns: 'io.metamask', provider: { request: vi.fn() } } ] const walletStandardWallets = [ { uuid: 'phantom-1', name: 'Phantom', chains: ['solana:mainnet'], features: ['standard:connect'], adapter: { connect: vi.fn() } } ] const tronWallets = [ { uuid: 'tron-tronlink', name: 'tronLink', injectedId: 'tronLink', provider: { tronWeb: {} } } ] mockWrappedAPI = createMockParentAPI({ eip6963Wallets, walletStandardWallets, tronWallets }) await createBridgeChildInIframe({ tronInjectedIds: ['tronLink'] }) await vi.advanceTimersByTimeAsync(500) expect((window as any).eip6963Wallets).toHaveLength(1) expect((window as any).walletStandardWallets).toHaveLength(1) expect((window as any).tronWallets).toHaveLength(1) }) it('should handle empty wallet arrays', async () => { mockWrappedAPI = createMockParentAPI({ eip6963Wallets: [], walletStandardWallets: [], tronWallets: [] }) await createBridgeChildInIframe() await vi.advanceTimersByTimeAsync(500) expect((window as any).eip6963Wallets).toEqual([]) expect((window as any).walletStandardWallets).toEqual([]) expect((window as any).tronWallets).toEqual([]) }) }) describe('reportBridgeError (P6)', () => { beforeEach(() => { // No iframe parent → the constructor's initializeConnection returns early, // so we exercise reportBridgeError without spinning the poll loop. Object.defineProperty(window, 'parent', { value: window, writable: true, configurable: true }) }) afterEach(() => { Object.defineProperty(window, 'parent', { value: originalParent, writable: true, configurable: true }) }) it('reports a real failure once per (namespace, message); skips benign timeouts', async () => { const { BridgeChild } = await import('./BridgeChild') const { BridgeReadTimeout } = await import('./bridge-timing') const errors: Array<{ namespace: string; message: string }> = [] const child = new BridgeChild({ onError: e => errors.push(e) }) child['reportBridgeError']('eip155', new Error('marshal failed')) child['reportBridgeError']('eip155', new Error('marshal failed')) // dedup child['reportBridgeError']('tvm', new BridgeReadTimeout()) // benign → skip child['reportBridgeError']('tron', new Error('older parent')) expect(errors).toEqual([ { namespace: 'eip155', message: 'marshal failed' }, { namespace: 'tron', message: 'older parent' } ]) }) it('is a no-op when no onError sink is supplied', async () => { const { BridgeChild } = await import('./BridgeChild') const child = new BridgeChild() expect(() => child['reportBridgeError']('eip155', new Error('x')) ).not.toThrow() }) it('never throws for an error value with a throwing toString()', async () => { const { BridgeChild } = await import('./BridgeChild') const errors: Array<{ namespace: string; message: string }> = [] const child = new BridgeChild({ onError: e => errors.push(e) }) const evil = { toString(): string { throw new Error('poisoned toString') } } expect(() => child['reportBridgeError']('eip155', evil)).not.toThrow() expect(errors).toEqual([ { namespace: 'eip155', message: 'Unreadable error object' } ]) }) it('caps a huge error message so the dedup set stays bounded', async () => { const { BridgeChild } = await import('./BridgeChild') const errors: Array<{ namespace: string; message: string }> = [] const child = new BridgeChild({ onError: e => errors.push(e) }) child['reportBridgeError']('eip155', new Error('x'.repeat(10_000))) expect(errors[0]?.message).toHaveLength(500) }) it('swallows a throwing onError sink — telemetry must not kill the poll loop', async () => { const { BridgeChild } = await import('./BridgeChild') const child = new BridgeChild({ onError: () => { throw new Error('consumer sink exploded') } }) // Invoked from inside the tryMarshal* catch blocks: a propagating throw // would reject the poll loop's Promise.all and stop discovery forever. expect(() => child['reportBridgeError']('eip155', new Error('marshal failed')) ).not.toThrow() }) it('bounds the dedup set — an evicted (namespace, message) reports again past the cap', async () => { const { BridgeChild } = await import('./BridgeChild') const errors: Array<{ namespace: string; message: string }> = [] const child = new BridgeChild({ onError: e => errors.push(e) }) const cap = BridgeChild['MAX_REPORTED_BRIDGE_ERRORS'] const report = (m: string) => child['reportBridgeError']('eip155', new Error(m)) for (let i = 0; i < cap; i++) report(`err-${i}`) expect(errors).toHaveLength(cap) report('err-0') // still deduped expect(errors).toHaveLength(cap) report('over-cap') // trips cap → evict → reports expect(errors).toHaveLength(cap + 1) report('err-0') // evicted → reports again, proving the set stays bounded expect(errors).toHaveLength(cap + 2) }) }) })