// @ts-nocheck import * as Comlink from 'comlink' import { hasInFrameTonBridge } from './tonInFrameBridge' import { MAX_POLL_MS, POLL_INTERVAL_MS, raceParentRead, BridgeReadTimeout } from './bridge-timing' // Define the expected parent API interface locally interface ParentAPI { eip6963Wallets: unknown[] eip6963WalletsReady: boolean walletStandardWallets: unknown[] walletStandardWalletsReady: boolean bip122Wallets: unknown[] bip122WalletsReady: boolean tronWallets: unknown[] tronWalletsReady: boolean tonWallets: unknown[] tonWalletsReady: boolean parentOrigin: string discoverTronWallets: (injectedIds: string[]) => void discoverTonWallets: (jsBridgeKeys: string[]) => void subscribeEip6963ProviderEvent: ( uuid: string, eventName: string, callback: (payload?: unknown) => void, rdns?: string ) => Promise<(() => void) | undefined> subscribeTronProviderEvent: ( injectedId: string, eventName: string, callback: (payload?: unknown) => void ) => (() => void) | undefined subscribeSolanaWalletEvent: ( walletId: string, callback: (address: string | null) => void ) => (() => void) | undefined subscribeBip122WalletEvent: ( walletId: string, callback: (address: string | null) => void ) => (() => void) | undefined } /** * Extract a bounded message from any thrown value without ever throwing — * local copy of `safeErrorMessage` (@meshconnect/uwc-types); this package * deliberately stays dependency-free (comlink only); keep the two in sync. * A poisoned getter / throwing toString() would otherwise kill the poll loop, * and an unbounded message retained as a dedup key is a memory footgun. */ function safeErrorMessage(error: unknown): string { try { const message = error instanceof Error ? error.message : String(error) return message.length > 500 ? message.slice(0, 500) : message } catch { return 'Unreadable error object' } } /** * Rebuild a bip122 account the parent flattened for the wire. * * `BridgeParent.toBip122WireAccount` sends `publicKey` as a number array, * because Comlink's structured clone drops the wallet's prototype-accessor * fields entirely. Reviving it to a `Uint8Array` here means the injected * adapter sees exactly the shape it sees in direct mode, so nothing downstream * needs to know whether it is running framed. */ export function reviveBip122Account(account: unknown): unknown { const a = account as { address?: string; publicKey?: number[] | Uint8Array } if (!a || typeof a !== 'object') return account // An OLDER parent (between the bip122 wiring in #237 and the marshaling fix) // sends the wallet's own account objects, which structured clone empties to // `{}`. Reviving one would manufacture `publicKey: Uint8Array []` — the // adapter then hexes it to `''`, keeps the account as truthy, and commits a // session with `address: undefined`. Both halves are broken in that pairing // either way; handing the original back keeps it failing loudly at // `bytesToHex` instead of surfacing as an unexplained address mismatch. if (typeof a.address !== 'string') return account return { ...a, publicKey: a.publicKey instanceof Uint8Array ? a.publicKey : Uint8Array.from(a.publicKey ?? []) } } export class BridgeChild { private parentAPI?: Comlink.Remote private tronInjectedIds: string[] private tonJsBridgeKeys: string[] // Per-namespace completion flags so we only marshal each set once. private eip6963Done = false private solanaDone = false private bitcoinDone = false private tronDone = false private tonDone = false // Where each marshaled bip122 wallet sits in the parent's `bip122Wallets`, // keyed by uuid, so its accounts can be re-read later. private bip122ParentIndex = new Map() // Report a bridge-discovery failure to the consumer (wired to UWC's observer). // Optional; default no-op preserves the historical silent behaviour. private onError?: (info: { namespace: string; message: string }) => void // Dedup so the per-tick retry loop can't storm the observer with the same error. // Bounded (storm guard, not a permanent ledger): evicted wholesale past the cap // so a long session with high-cardinality messages can't grow it without bound. // Local copy of `createBoundedDedup` (@meshconnect/uwc-types) — this package // deliberately stays dependency-free (comlink only); keep the two in sync. private reportedBridgeErrors = new Set() private static readonly MAX_REPORTED_BRIDGE_ERRORS = 100 constructor(options?: { tronInjectedIds?: string[] tonJsBridgeKeys?: string[] onError?: (info: { namespace: string; message: string }) => void }) { this.tronInjectedIds = options?.tronInjectedIds ?? [] this.tonJsBridgeKeys = options?.tonJsBridgeKeys ?? [] this.onError = options?.onError this.initializeConnection() } /** * Surface a bridge-discovery failure ONCE per (namespace, message). Benign * poll-misses (`BridgeReadTimeout` — the parent isn't live yet, retried next * tick) are NOT reported; only real failures (older/unsupported parent, * malformed marshaling) reach the observer. */ private reportBridgeError(namespace: string, err: unknown): void { if (!this.onError) return if (err instanceof BridgeReadTimeout) return const message = safeErrorMessage(err) const key = `${namespace}:${message}` if (this.reportedBridgeErrors.has(key)) return if ( this.reportedBridgeErrors.size >= BridgeChild.MAX_REPORTED_BRIDGE_ERRORS ) { this.reportedBridgeErrors.clear() } this.reportedBridgeErrors.add(key) try { this.onError({ namespace, message }) } catch { // A throwing consumer sink is invoked from inside the tryMarshal* catch // blocks, whose rejection would kill the fire-and-forget poll() loop and // silently stop wallet discovery for ALL namespaces. Telemetry must // never break the bridge. } } private async initializeConnection(): Promise { if (!window.parent || window.parent === window) { return } window.UWCBridgeChildInitialized = true // If another bootstrap already published at least one non-empty wallet // array, skip everything. Matches the old BridgeChild semantics for // embedded flows. Note: a previously-set empty array (`[]`, distinct from // `undefined`) does NOT short-circuit us — another module saying "I // couldn't find any EVM wallets" shouldn't prevent us from still // discovering TON/Tron via the bridge. if (this.anyWindowWalletsAlreadySet()) { return } this.parentAPI = Comlink.wrap( Comlink.windowEndpoint(window.parent, self, '*') ) // Tron/TON discovery is driven from the poll loop (tryMarshalTron/Ton), // which re-issues discoverTron/TonWallets every tick until the parent // answers. A single eager trigger here would be silently lost if it raced // the parent's Comlink.expose (Comlink calls hang, never reject). // Fetch the parent origin concurrently for TON Connect manifest URL. this.syncParentOrigin() this.pollForWallets() this.installProviderEventSubscriptionGlobals() this.installBip122AccountsRefresh() } /** * Install `window.__uwcRefreshBip122Accounts(walletId)`, which re-reads a * bip122 wallet's accounts from the parent into the copy marshaled here. * * `tryMarshalBitcoin` copies `accounts` once, at startup, and a grant usually * lands later: an EVM or Solana connect to MetaMask grants its Bitcoin * account too. The injected connector calls this before it reads `accounts`, * so a framed session gathers that account the way a direct one does. The * marshaled wallet is updated in place because the connector holds that same * object. * * Best-effort: an unknown wallet or a failed read leaves the copy as it was. * An older parent built its list once, so re-reading it changes nothing. */ private installBip122AccountsRefresh(): void { const parentAPI = this.parentAPI if (!parentAPI) return window.__uwcRefreshBip122Accounts = async ( walletId: string ): Promise => { const index = this.bip122ParentIndex.get(walletId) const local = (window.walletStandardBitcoinWallets ?? []).find( wallet => wallet?.uuid === walletId ) if (index === undefined || !local) return try { const entry = parentAPI.bip122Wallets[index] const [uuid, accounts] = await raceParentRead( Promise.all([entry.uuid, entry.wallet.accounts]) ) // A rebuilt parent list could hold another wallet at this index; never // copy its accounts onto this one. if (uuid !== walletId || !Array.isArray(accounts)) return local.wallet.accounts = accounts.map(reviveBip122Account) } catch (err) { this.reportBridgeError('bip122', err) } } } /** * Install window globals the injected EVM/TRON connectors call directly to * subscribe to live provider events across the bridge (accountsChanged, * chainChanged, disconnect) — mirrors this file's existing convention of * exposing bridge capability via `window.*` rather than requiring callers * to hold a `BridgeChild` instance reference (see `window.eip6963Wallets` * etc. above). Only installed once `this.parentAPI` exists, i.e. only in * bridge mode. */ private installProviderEventSubscriptionGlobals(): void { const parentAPI = this.parentAPI if (!parentAPI) return window.__uwcSubscribeEip6963ProviderEvent = ( uuid: string, eventName: string, callback: (payload?: unknown) => void, rdns?: string ) => { const proxiedCallback = Comlink.proxy(callback) let unsubscribe: (() => void) | null = null let torndown = false Promise.resolve( parentAPI.subscribeEip6963ProviderEvent( uuid, eventName, proxiedCallback, rdns ) ) .then((unsub: unknown) => { if (torndown) { if (typeof unsub === 'function') unsub() return } unsubscribe = typeof unsub === 'function' ? unsub : null }) .catch((err: unknown) => { // A rejection here means the parent's uuid lookup genuinely found // nothing (see BridgeParent.ts's subscribeEip6963ProviderEvent) — // most commonly the uuid-mismatch bug from a wallet also // discovered locally inside this iframe. Report it instead of // letting it surface as a silent, undetectable no-op. this.reportBridgeError('eip155', err) }) return () => { torndown = true if (unsubscribe) unsubscribe() } } window.__uwcSubscribeTronProviderEvent = ( injectedId: string, eventName: string, callback: (payload?: unknown) => void ) => { const proxiedCallback = Comlink.proxy(callback) let unsubscribe: (() => void) | null = null let torndown = false Promise.resolve( parentAPI.subscribeTronProviderEvent( injectedId, eventName, proxiedCallback ) ) .then((unsub: unknown) => { if (torndown) { if (typeof unsub === 'function') unsub() return } unsubscribe = typeof unsub === 'function' ? unsub : null }) .catch((err: unknown) => { // Same rationale as the EIP-6963 catch above. this.reportBridgeError('tron', err) }) return () => { torndown = true if (unsubscribe) unsubscribe() } } window.__uwcSubscribeSolanaWalletEvent = ( walletId: string, callback: (address: string | null) => void ) => { const proxiedCallback = Comlink.proxy(callback) let unsubscribe: (() => void) | null = null let torndown = false Promise.resolve( parentAPI.subscribeSolanaWalletEvent(walletId, proxiedCallback) ) .then((unsub: unknown) => { if (torndown) { if (typeof unsub === 'function') unsub() return } unsubscribe = typeof unsub === 'function' ? unsub : null }) .catch((err: unknown) => { // A rejection here means the parent's walletId lookup genuinely // found nothing (see BridgeParent.ts's subscribeSolanaWalletEvent) // — report it instead of letting it surface as a silent, // undetectable no-op. this.reportBridgeError('solana', err) }) return () => { torndown = true if (unsubscribe) unsubscribe() } } window.__uwcSubscribeBip122WalletEvent = ( walletId: string, callback: (address: string | null) => void ) => { const proxiedCallback = Comlink.proxy(callback) let unsubscribe: (() => void) | null = null let torndown = false Promise.resolve( parentAPI.subscribeBip122WalletEvent(walletId, proxiedCallback) ) .then((unsub: unknown) => { if (torndown) { if (typeof unsub === 'function') unsub() return } unsubscribe = typeof unsub === 'function' ? unsub : null }) .catch((err: unknown) => { // A rejection here means the parent's walletId lookup genuinely // found nothing (see BridgeParent.ts's subscribeBip122WalletEvent) // — report it instead of letting it surface as a silent, // undetectable no-op. this.reportBridgeError('bip122', err) }) return () => { torndown = true if (unsubscribe) unsubscribe() } } } private anyWindowWalletsAlreadySet(): boolean { return Boolean( (window.eip6963Wallets && window.eip6963Wallets.length > 0) || (window.walletStandardWallets && window.walletStandardWallets.length > 0) || (window.walletStandardBitcoinWallets && window.walletStandardBitcoinWallets.length > 0) || (window.tronWallets && window.tronWallets.length > 0) || (window.tonWallets && window.tonWallets.length > 0) ) } private async syncParentOrigin(): Promise { // Same late-expose hazard as the wallet poll: a parentOrigin read posted // before the parent's Comlink.expose hangs forever (the request message is // dropped, so it never resolves even once the parent comes up). Retry with a // per-read deadline until the parent answers or the poll budget elapses. // A *resolved* read is final, not retried: the current BridgeParent sets // parentOrigin to window.location.origin synchronously before expose, so a // resolved value is always a real origin; a falsy resolve means an older // parent without parentOrigin, where spinning the full budget is pointless. const startTime = Date.now() while (Date.now() - startTime <= MAX_POLL_MS) { try { const origin = await raceParentRead(this.parentAPI?.parentOrigin) if (origin) window.uwcParentOrigin = origin return } catch (err) { if (err instanceof BridgeReadTimeout) { await new Promise(resolve => setTimeout(resolve, POLL_INTERVAL_MS)) continue } // Older BridgeParent that throws on parentOrigin — ignore. return } } } private pollForWallets(): void { const startTime = Date.now() const poll = async () => { if (!this.parentAPI) return if (Date.now() - startTime > MAX_POLL_MS) { this.fillEmptyDefaults() return } // Run all five namespace marshals concurrently. Each short-circuits if // already done or not yet ready, so the cost is a single // `await ready` round-trip per pending namespace per tick. await Promise.all([ this.tryMarshalEip6963(), this.tryMarshalSolana(), this.tryMarshalBitcoin(), this.tryMarshalTron(), this.tryMarshalTon() ]) // Tron/TON have no early default: tryMarshal{Tron,Ton} writes the real // wallets (or [] on a ready-with-empty / unsupported parent), and the // MAX_POLL_MS fillEmptyDefaults backstop covers a parent that never // reports ready. Writing [] earlier would race a still-pending discovery // and make the consumer's one-shot poll miss a wallet that lands a tick // later. if ( this.eip6963Done && this.solanaDone && this.bitcoinDone && this.tronDone && this.tonDone ) { return } setTimeout(poll, POLL_INTERVAL_MS) } // Kick off synchronously — no first-tick delay. poll() } private fillEmptyDefaults(): void { if (window.eip6963Wallets === undefined) window.eip6963Wallets = [] if (window.walletStandardWallets === undefined) { window.walletStandardWallets = [] } if (window.walletStandardBitcoinWallets === undefined) { window.walletStandardBitcoinWallets = [] } if (window.tronWallets === undefined) window.tronWallets = [] if (window.tonWallets === undefined) window.tonWallets = [] } /** * A readiness read that RESOLVES `undefined` means the parent is live but its * ParentAPI predates this namespace: real Comlink resolves a GET on a missing * property to `undefined` (it never rejects), while a not-yet-exposed parent * makes the read hang into a BridgeReadTimeout instead. Waiting cannot turn * that answer into `true`, so complete the namespace with [] now rather than * retrying to the MAX_POLL_MS backstop — on hosts embedding via an old SDK * (e.g. mesh-web-sdk 3.3.x shipping uwc-bridge-parent 0.0.2, which predates * tron/ton) that retry loop stalled consumer-side wallet detection ~5 s on * every load. Reported once per namespace so the "why didn't wallet X * appear?" class stays observable. */ private completeUnsupportedNamespace( namespace: 'eip155' | 'solana' | 'tron' | 'tvm' | 'bip122' ): void { this.reportBridgeError( namespace, new Error( 'parent bridge does not expose this namespace (older uwc-bridge-parent)' ) ) if (namespace === 'eip155') { if (window.eip6963Wallets === undefined) window.eip6963Wallets = [] this.eip6963Done = true } else if (namespace === 'solana') { if (window.walletStandardWallets === undefined) { window.walletStandardWallets = [] } this.solanaDone = true } else if (namespace === 'tron') { if (window.tronWallets === undefined) window.tronWallets = [] this.tronDone = true } else if (namespace === 'bip122') { if (window.walletStandardBitcoinWallets === undefined) { window.walletStandardBitcoinWallets = [] } this.bitcoinDone = true } else { if (window.tonWallets === undefined) window.tonWallets = [] this.tonDone = true } } private async tryMarshalEip6963(): Promise { if (this.eip6963Done || !this.parentAPI) return try { const ready = await raceParentRead(this.parentAPI.eip6963WalletsReady) if (ready === undefined) { this.completeUnsupportedNamespace('eip155') return } if (!ready) return const len = await this.parentAPI.eip6963Wallets.length const wallets: unknown[] = [] if (len > 0) { const indices = Array.from({ length: len }, (_, i) => i) const marshalled = await Promise.all( indices.map(async i => { const entry = this.parentAPI!.eip6963Wallets[i] const [uuid, name, icon, rdns] = await Promise.all([ entry.uuid, entry.name, entry.icon, entry.rdns ]) return { uuid, name, icon, rdns, provider: entry.provider } }) ) wallets.push(...marshalled) } window.eip6963Wallets = wallets this.eip6963Done = true } catch (err) { // retry on next tick; surface only a real (non-timeout) failure, once. this.reportBridgeError('eip155', err) } } private async tryMarshalSolana(): Promise { if (this.solanaDone || !this.parentAPI) return try { const ready = await raceParentRead( this.parentAPI.walletStandardWalletsReady ) if (ready === undefined) { this.completeUnsupportedNamespace('solana') return } if (!ready) return const len = await this.parentAPI.walletStandardWallets.length const wallets: unknown[] = [] if (len > 0) { const indices = Array.from({ length: len }, (_, i) => i) const marshalled = await Promise.all( indices.map(async i => { const entry = this.parentAPI!.walletStandardWallets[i] const [uuid, name, chains, features] = await Promise.all([ entry.uuid, entry.name, entry.chains, entry.features ]) return { uuid, name, chains, features, adapter: entry.adapter } }) ) wallets.push(...marshalled) } window.walletStandardWallets = wallets this.solanaDone = true } catch (err) { // retry on next tick; surface only a real (non-timeout) failure, once. this.reportBridgeError('solana', err) } } private async tryMarshalBitcoin(): Promise { if (this.bitcoinDone || !this.parentAPI) return try { const ready = await raceParentRead(this.parentAPI.bip122WalletsReady) if (ready === undefined) { // Live parent without the bip122 API (older uwc-bridge-parent) — see // completeUnsupportedNamespace. Complete now with [] rather than // retrying to the MAX_POLL_MS backstop, matching every other namespace. this.completeUnsupportedNamespace('bip122') return } if (!ready) return const len = await this.parentAPI.bip122Wallets.length const wallets: unknown[] = [] if (len > 0) { const indices = Array.from({ length: len }, (_, i) => i) const marshalled = await Promise.all( indices.map(async i => { const entry = this.parentAPI!.bip122Wallets[i] // Each field is resolved individually — including each // `wallet.features['bitcoin:*']` entry — rather than awaiting // `entry.wallet` as one object. Comlink only checks a value's // proxy marker on the exact value a GET resolves to; a // Comlink.proxy()-wrapped feature method NESTED inside a larger // plain object never gets that check (the outer object wins RAW, // and postMessage's native structured clone then throws on the // function it contains). Resolving each feature as its own leaf // GET makes it the top-level value of that GET, so the proxy // marker is seen and a live callable proxy comes back (or // `undefined` for a feature the wallet doesn't support). const [ uuid, name, features, walletName, accounts, connectFeature, disconnectFeature, signMessageFeature, signTransactionFeature ] = await Promise.all([ entry.uuid, entry.name, entry.features, entry.wallet.name, entry.wallet.accounts, entry.wallet.features['bitcoin:connect'], // Carried so a framed child can REVOKE the origin's grant, not // just clear local state — without it a pinned-address connect // can never reach an account the origin wasn't granted. entry.wallet.features['bitcoin:disconnect'], entry.wallet.features['bitcoin:signMessage'], entry.wallet.features['bitcoin:signTransaction'] ]) return { uuid, name, features, wallet: { name: walletName, accounts: (accounts ?? []).map(reviveBip122Account), features: { // Wrap connect so the accounts it RETURNS are revived too — // they cross flattened for the same reason the snapshot // does, and the adapter reads `publicKey` off them // immediately (`bytesToHex`), which throws on a plain array. 'bitcoin:connect': connectFeature ? { connect: async (input: unknown) => { const result = (await connectFeature.connect( input )) as { accounts?: unknown[] } return { accounts: (result?.accounts ?? []).map( reviveBip122Account ) } } } : undefined, 'bitcoin:disconnect': disconnectFeature, 'bitcoin:signMessage': signMessageFeature, 'bitcoin:signTransaction': signTransactionFeature } } } }) ) wallets.push(...marshalled) // Two wallets can share a uuid (same name and chain). Keep the first, the // one a lookup by uuid finds, here and in the injected connector. marshalled.forEach((wallet, i) => { if (!this.bip122ParentIndex.has(wallet.uuid)) { this.bip122ParentIndex.set(wallet.uuid, i) } }) } window.walletStandardBitcoinWallets = wallets this.bitcoinDone = true } catch (err) { // retry on next tick; surface only a real (non-timeout) failure, once. this.reportBridgeError('bip122', err) } } private async tryMarshalTron(): Promise { if (this.tronDone || !this.parentAPI) return // (Re-)ask the parent to run Tron discovery on every tick. A one-shot // trigger is silently lost if posted before the parent's Comlink.expose (the // request hangs, never rejects), so re-issuing mirrors EIP-6963's per-tick // resilience. Comlink calls return a Promise and never throw synchronously, // so an unsupported parent is handled by the tronWalletsReady read below (or // the MAX_POLL_MS backstop) — not here. The try only guards a non-Comlink // stub whose call throws synchronously. // Each pre-expose reissue leaves one lightweight Comlink pending-listener // Map entry (requestResponseMessage — not a DOM listener or MessageChannel // port); bounded by the expose delay and GC'd. An in-flight guard is // intentionally avoided: it would deadlock recovery, since a never-settling // pre-expose call would block all subsequent re-issues. // // Fired in a detached async IIFE so that the await — needed to make the // try/catch absorb both sync throws (test stubs) and async rejections — // does not block this tick. A pre-expose hang sits inside the IIFE // harmlessly until the parent comes up or GC reaps it. void (async () => { try { await this.parentAPI.discoverTronWallets?.(this.tronInjectedIds) } catch { // absorb — the readiness read below governs the outcome } })() let ready try { ready = await raceParentRead(this.parentAPI.tronWalletsReady) } catch (err) { // Read timed out → parent not live yet, retry next tick. Any other error // (older parent throwing on the property) → no Tron support. if (err instanceof BridgeReadTimeout) { return } // Older / unsupported parent throwing on the property → no Tron via bridge. this.reportBridgeError('tron', err) window.tronWallets = [] this.tronDone = true return } if (ready === undefined) { // Live parent without the Tron API — see completeUnsupportedNamespace. this.completeUnsupportedNamespace('tron') return } if (!ready) return try { const len = await this.parentAPI.tronWallets.length const wallets: unknown[] = [] if (len > 0) { const indices = Array.from({ length: len }, (_, i) => i) const marshalled = await Promise.all( indices.map(async i => { const entry = this.parentAPI!.tronWallets[i] const [uuid, name, injectedId] = await Promise.all([ entry.uuid, entry.name, entry.injectedId ]) return { uuid, name, injectedId, provider: entry.provider } }) ) wallets.push(...marshalled) } window.tronWallets = wallets this.tronDone = true } catch (err) { this.reportBridgeError('tron', err) window.tronWallets = [] this.tronDone = true } } private async tryMarshalTon(): Promise { if (this.tonDone || !this.parentAPI) return // Re-issue discovery each tick — same expose-race resilience as Tron. // See tryMarshalTron for the detached-IIFE rationale. void (async () => { try { await this.parentAPI.discoverTonWallets?.(this.tonJsBridgeKeys) } catch { // absorb — the readiness read below governs the outcome } })() let ready try { ready = await raceParentRead(this.parentAPI.tonWalletsReady) } catch (err) { if (err instanceof BridgeReadTimeout) return this.reportBridgeError('tvm', err) window.tonWallets = [] this.tonDone = true return } if (ready === undefined) { // Live parent without the TON API — see completeUnsupportedNamespace. this.completeUnsupportedNamespace('tvm') return } if (!ready) return try { const len = await this.parentAPI.tonWallets.length const wallets: Array<{ uuid: string name: string icon: string jsBridgeKey: string provider: any }> = [] if (len > 0) { const indices = Array.from({ length: len }, (_, i) => i) const marshalled = await Promise.all( indices.map(async i => { const entry = this.parentAPI!.tonWallets[i] const [uuid, name, icon, jsBridgeKey] = await Promise.all([ entry.uuid, entry.name, entry.icon, entry.jsBridgeKey ]) return { uuid, name, icon, jsBridgeKey, provider: entry.provider } }) ) wallets.push(...marshalled) } window.tonWallets = wallets // Shim window[jsBridgeKey].tonconnect so @tonconnect/sdk finds the // Comlink proxy. Static props must be sync, but Comlink returns // Promises — so we prefetch them here in parallel. await Promise.all( wallets.map(async wallet => { if (!wallet.jsBridgeKey || !wallet.provider) return // Keep the real in-frame provider so connect() attributes to the // iframe origin; shimming would attribute to the parent, which the // wallet's manifest origin check rejects. if (hasInFrameTonBridge(wallet.jsBridgeKey)) return const proxy = wallet.provider const [deviceInfo, walletInfo, protocolVersion, isWalletBrowser] = await Promise.all([ proxy.deviceInfo, proxy.walletInfo, proxy.protocolVersion, proxy.isWalletBrowser ]) ;(window as any)[wallet.jsBridgeKey] = { tonconnect: { deviceInfo, walletInfo, protocolVersion: protocolVersion ?? 2, isWalletBrowser: isWalletBrowser ?? false, connect: (ver: number, msg: unknown) => proxy.connect(ver, msg), restoreConnection: () => proxy.restoreConnection(), send: (msg: unknown) => proxy.send(msg), listen: (callback: (event: unknown) => void) => { const proxiedCallback = Comlink.proxy(callback) let unsubscribe: (() => void) | null = null const result = proxy.listen(proxiedCallback) Promise.resolve(result).then((unsub: unknown) => { unsubscribe = typeof unsub === 'function' ? unsub : () => {} }) return () => { if (unsubscribe) unsubscribe() } }, disconnect: () => proxy.disconnect?.() } } }) ) this.tonDone = true } catch (err) { // Parent doesn't support TON — mark done with empty list. this.reportBridgeError('tvm', err) window.tonWallets = [] this.tonDone = true } } }