diff --git a/ui/app/AppLayouts/Browser/provider/js/eip6963_announcer.js b/ui/app/AppLayouts/Browser/provider/js/eip6963_announcer.js new file mode 100644 index 00000000000..b6d74e2e7f9 --- /dev/null +++ b/ui/app/AppLayouts/Browser/provider/js/eip6963_announcer.js @@ -0,0 +1,60 @@ +"use strict"; + +// EIP-6963: Multi Injected Provider Discovery +// https://eips.ethereum.org/EIPS/eip-6963 +// This script announces the Status provider so dApps can discover it + +(function() { + const STATUS_PROVIDER_INFO = { + uuid: "c14d6a7e-14c2-477d-bcb7-ffb732145eae", + name: "Status", + icon: "data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzIiIGhlaWdodD0iMzIiIHZpZXdCb3g9IjAgMCAzMiAzMiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4gPGcgY2xpcC1wYXRoPSJ1cmwoI2NsaXAwXzk1MF8xMjM5NikiPiA8bWFzayBpZD0ibWFzazBfOTUwXzEyMzk2IiBzdHlsZT0ibWFzay10eXBlOmFscGhhIiBtYXNrVW5pdHM9InVzZXJTcGFjZU9uVXNlIiB4PSIwIiB5PSItMSIgd2lkdGg9IjMyIiBoZWlnaHQ9IjMzIj4gPHBhdGggZD0iTTE2IC0wLjAwMDQ4ODI4MUM0IC0wLjAwMDQ4ODI4MSAwIDMuOTk5NTEgMCAxNS45OTk1QzAgMjcuOTk5NSA0IDMxLjk5OTUgMTYgMzEuOTk5NUMyOCAzMS45OTk1IDMyIDI3Ljk5OTUgMzIgMTUuOTk5NUMzMiAzLjk5OTUxIDI4IC0wLjAwMDQ4ODI4MSAxNiAtMC4wMDA0ODgyODFaIiBmaWxsPSJ3aGl0ZSIvPiA8L21hc2s+IDxnIG1hc2s9InVybCgjbWFzazBfOTUwXzEyMzk2KSI+IDxnIGZpbHRlcj0idXJsKCNmaWx0ZXIwX2ZfOTUwXzEyMzk2KSI+IDxjaXJjbGUgY3g9IjIzIiBjeT0iOC45OTk1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tncm91bmRJbWFnZUZpeCIgcmVzdWx0PSJzaGFwZSIvPiA8ZmVHYXVzc2lhbkJsdXIgc3RkRGV2aWF0aW9uPSI0LjcxNTEzIiByZXN1bHQ9ImVmZmVjdDFfZm9yZWdyb3VuZEJsdXJfOTUwXzEyMzk2Ii8+IDwvZmlsdGVyPiA8ZmlsdGVyIGlkPSJmaWx0ZXIzX2ZfOTUwXzEyMzk2IiB4PSItMzUuNDMwMyIgeT0iLTE5LjQzMDciIHdpZHRoPSI1Ni44NjA1IiBoZWlnaHQ9IjU2Ljg2MDUiIGZpbHRlclVuaXRzPSJ1c2VyU3BhY2VPblVzZSIgY29sb3ItaW50ZXJwb2xhdGlvbi1maWx0ZXJzPSJzUkdCIj4gPGZlRmxvb2QgZmxvb2Qtb3BhY2l0eT0iMCIgcmVzdWx0PSJCYWNrZ3JvdW5kSW1hZ2VGaXgiLz4gPGZlQmxlbmQgbW9kZT0ibm9ybWFsIiBpbj0iU291cmNlR3JhcGhpYyIgaW4yPSJCYWNrZ3JvdW5kSW1hZ2VGaXgiIHJlc3VsdD0ic2hhcGUiLz4gPGZlR2F1c3NpYW5CbHVyIHN0ZERldmlhdGlvbj0iNC43MTUxMyIgcmVzdWx0PSJlZmZlY3QxX2ZvcmVncm91bmRCbHVyXzk1MF8xMjM5NiIvPiA8L2ZpbHRlcj4gPGNsaXBQYXRoIGlkPSJjbGlwMF85NTBfMTIzOTYiPiA8cmVjdCB3aWR0aD0iMzIiIGhlaWdodD0iMzIiIGZpbGw9IndoaXRlIi8+IDwvY2xpcFBhdGg+IDwvZGVmcz4gPC9zdmc+", + rdns: "app.status" + }; + + let retryCount = 0; + const MAX_RETRIES = 50; + const RETRY_DELAY = 100; + + function announceProvider() { + // Wait for window.ethereum to be available (injected by ethereum_wrapper.js) + if (!window.ethereum) { + if (retryCount >= MAX_RETRIES) { + console.error('[EIP-6963] Max retries reached, window.ethereum not available'); + return; + } + + retryCount++; + console.log(`[EIP-6963] window.ethereum not yet available, retry ${retryCount}/${MAX_RETRIES}`); + + setTimeout(announceProvider, RETRY_DELAY); + return; + } + + const detail = Object.freeze({ + info: STATUS_PROVIDER_INFO, + provider: window.ethereum + }); + + window.dispatchEvent( + new CustomEvent('eip6963:announceProvider', { detail }) + ); + + console.log('[EIP-6963] Status provider announced'); + } + + // Listen for discovery requests from dApps + window.addEventListener('eip6963:requestProvider', () => { + console.log('[EIP-6963] Provider discovery requested'); + announceProvider(); + }); + + // Announce provider when DOM is ready + if (document.readyState === 'loading') { + document.addEventListener('DOMContentLoaded', announceProvider); + } else { + // DOM already loaded, announce immediately (after ethereum is injected) + setTimeout(announceProvider, 0); + } + +})(); diff --git a/ui/app/AppLayouts/Browser/provider/js/ethereum_injector.js b/ui/app/AppLayouts/Browser/provider/js/ethereum_injector.js new file mode 100644 index 00000000000..cc5b45dd47a --- /dev/null +++ b/ui/app/AppLayouts/Browser/provider/js/ethereum_injector.js @@ -0,0 +1,33 @@ +function initializeWebChannel() { + if (typeof qt !== 'undefined' && qt.webChannelTransport) { + console.log("[Ethereum Injector] WebChannel transport available, initializing..."); + + try { + new QWebChannel(qt.webChannelTransport, setupEthereumProvider); + } catch (error) { + console.error("[Ethereum Injector] Error initializing WebChannel:", error); + } + } +} + +initializeWebChannel(); + +function setupEthereumProvider(channel) { + window.ethereumProvider = channel.objects.ethereumProvider; // Eip1193ProviderAdapter.qml + + if (!window.ethereumProvider) { + console.error("[Ethereum Injector] ethereumProvider not found in channel.objects"); + return; + } + + console.log("[Ethereum Injector] ethereumProvider exposed to window"); + + // Install the EIP-1193 js wrapper + if (typeof EthereumWrapper !== 'undefined' && EthereumWrapper.install) { + EthereumWrapper.install(); + } else { + console.error("[Ethereum Injector] EthereumWrapper not available"); + } +} + + diff --git a/ui/app/AppLayouts/Browser/provider/js/ethereum_wrapper.js b/ui/app/AppLayouts/Browser/provider/js/ethereum_wrapper.js new file mode 100644 index 00000000000..a73de9612f9 --- /dev/null +++ b/ui/app/AppLayouts/Browser/provider/js/ethereum_wrapper.js @@ -0,0 +1,389 @@ +"use strict"; + +// IIFE start (https://developer.mozilla.org/ru/docs/Glossary/IIFE) +const EthereumWrapper = (function() { + if (window.__ETHEREUM_WRAPPER_INSTANCE__) { + return window.__ETHEREUM_WRAPPER_INSTANCE__; + } + + // Manages EIP-1193 provider wrapper around Qml ethereum object (EIP1193ProviderAdapter.qml) + class EthereumProvider extends EventTarget { + constructor(nativeEthereum) { + super(); + + if (!nativeEthereum) { + console.error("[Ethereum Wrapper] nativeEthereum is not available"); + throw new Error("nativeEthereum is required"); + } + + this.listeners = new Map(); // event -> Set + this.nativeEthereum = nativeEthereum; + this.requestIdCounter = 1; // async requests + this.pendingRequests = new Map(); // requestId -> { resolve, reject, timestamp } + this.requestTimeout = 600000; // 10min timeout for pending requests. (nim side has it's own timeouts) + this.timeoutCheckInterval = 10000; + + // Wire native signals to events + this._wireSignals(); + + // Setup page unload handler + this._setupPageUnloadHandler(); + this._startTimeoutChecker(); + + // Set up EIP-1193 properties from QML + this.isStatus = nativeEthereum.isStatus !== undefined ? nativeEthereum.isStatus : true; + this.isMetaMask = nativeEthereum.isMetaMask !== undefined ? nativeEthereum.isMetaMask : false; + this.chainId = null; // Will be set on first eth_chainId request or providerStateChanged event + this.networkVersion = null; // decimal string format (deprecated) + this.selectedAddress = null; // current active address + this._connected = false; + } + + _connectSignal(eventName, handler) { + const event = this.nativeEthereum[eventName]; + if (event && event.connect) { + event.connect(handler); + return true; + } + return false; + } + + _rejectRequests(requestsToReject, deleteFromPending = false) { + for (const [requestId, entry, error] of requestsToReject) { + try { + entry.reject(error); + } catch (e) { + console.error('[Ethereum Wrapper] Error rejecting request:', e); + } + if (deleteFromPending) { + this.pendingRequests.delete(requestId); + } + } + } + + _rejectAllPendingRequests(error) { + const requestsToReject = Array.from(this.pendingRequests.entries()) + .map(([requestId, entry]) => [requestId, entry, error]); + this.pendingRequests.clear(); + this._rejectRequests(requestsToReject, false); + } + + _checkTimedOutRequests() { + const now = Date.now(); + const timedOutRequests = []; + + for (const [requestId, entry] of this.pendingRequests.entries()) { + if (now - entry.timestamp > this.requestTimeout) { + timedOutRequests.push([ + requestId, + entry, + { + code: -32603, + message: `Request timed out after ${this.requestTimeout}ms` + } + ]); + } + } + + if (timedOutRequests.length > 0) { + console.warn('[Ethereum Wrapper] Found', timedOutRequests.length, 'timed out requests'); + this._rejectRequests(timedOutRequests, true); + } + } + + _startTimeoutChecker() { + if (this.timeoutCheckIntervalId) { + return; + } + + this.timeoutCheckIntervalId = setInterval(() => { + if (this.pendingRequests.size > 0) { + this._checkTimedOutRequests(); + } + }, this.timeoutCheckInterval); + } + + _stopTimeoutChecker() { + if (this.timeoutCheckIntervalId) { + clearInterval(this.timeoutCheckIntervalId); + this.timeoutCheckIntervalId = null; + } + } + + _setupPageUnloadHandler() { + window.addEventListener('beforeunload', () => { + this._stopTimeoutChecker(); + this._rejectAllPendingRequests({ + code: -32603, + message: 'Page is being unloaded' + }); + }); + } + + _wireSignals() { + this._connectSignal('connectEvent', (info) => { + this._emit('connect', info); + }); + + this._connectSignal('disconnectEvent', (error) => { + this._rejectAllPendingRequests({ + code: 4900, + message: 'Provider disconnected' + }); + + this._emit('disconnect', error); + }); + + this._connectSignal('messageEvent', (message) => { + this._emit('message', message); + }); + + this._connectSignal('chainChangedEvent', (chainId) => { + this._emit('chainChanged', chainId); + }); + + this._connectSignal('accountsChangedEvent', (accounts) => { + this._emit('accountsChanged', accounts); + }); + + // Provider state changed - update all properties at once + this._connectSignal('providerStateChanged', () => { + this.isStatus = this.nativeEthereum.isStatus !== undefined ? this.nativeEthereum.isStatus : this.isStatus; + this.isMetaMask = this.nativeEthereum.isMetaMask !== undefined ? this.nativeEthereum.isMetaMask : this.isMetaMask; + this.chainId = this.nativeEthereum.chainId || this.chainId; + this.networkVersion = this.nativeEthereum.networkVersion || this.networkVersion; + this.selectedAddress = this.nativeEthereum.selectedAddress || null; + this._connected = this.nativeEthereum.connected !== undefined ? this.nativeEthereum.connected : this._connected; + }); + + // Handle async RPC responses + this._connectSignal('requestCompletedEvent', this.handleRequestCompleted.bind(this)); + } + + _emit(event, ...args) { + const set = this.listeners.get(event); + if (!set) return; + for (const handler of set) { + try { + handler(...args); + } catch (e) { + console.error("[Ethereum Wrapper] handler error", e); + } + } + } + + isConnected() { + return this._connected; + } + + request(args) { + if (!args || typeof args !== 'object' || !args.method) { + return Promise.reject({ + code: -32602, + message: 'Invalid params: missing method' + }); + } + const requestId = this.requestIdCounter++; + const payload = Object.assign({}, args, { requestId }); + + return new Promise((resolve, reject) => { + this.pendingRequests.set(requestId, { + resolve, + reject, + method: args.method, + timestamp: Date.now() + }); + + try { + const nativeResp = this.nativeEthereum.request(payload); + + if (nativeResp && typeof nativeResp === 'string') { + try { + const parsedResp = JSON.parse(nativeResp); + if (parsedResp?.error) { + this.pendingRequests.delete(requestId); + reject(parsedResp.error); + return; + } + } catch {} + } + } catch (e) { + // Only catch synchronous exceptions (e.g., invalid payload) + this.pendingRequests.delete(requestId); + reject(e); + } + }); + } + + // Method for backward compatibility with older dApps + enable() { + return this.request({ method: 'eth_requestAccounts' }); + } + + _processResponse(resp, method, entry) { + if (resp && typeof resp === 'string') { + try { + const parsed = JSON.parse(resp); + resp = parsed; + } catch (e) { + entry.resolve(resp); + return; + } + } + + if (resp && resp.error) { + entry.reject(resp.error); + } else if (resp && resp.result !== undefined) { + entry.resolve(resp.result); + } else { + entry.resolve(resp); + } + } + + handleRequestCompleted(payload) { + const requestId = payload && (payload.requestId || (payload.response && payload.response.id)) || 0; + try { + const entry = this.pendingRequests.get(requestId); + + if (!entry) { + console.warn("[Ethereum Wrapper] No pending request found for ID:", requestId); + return; + } + + this._processResponse(payload && payload.response, entry.method, entry); + } catch (e) { + console.error('[Ethereum Wrapper] requestCompletedEvent handler error', e); + } finally { + if (requestId) { + this.pendingRequests.delete(requestId); + } + } + } + + on(event, handler) { + if (typeof handler !== 'function') return this; + const set = this.listeners.get(event) || new Set(); + set.add(handler); + this.listeners.set(event, set); + return this; + } + + once(event, handler) { + if (typeof handler !== 'function') return this; + const self = this; + function onceHandler() { + try { + handler.apply(null, arguments); + } finally { + self.removeListener(event, onceHandler); + } + } + return this.on(event, onceHandler); + } + + removeListener(event, handler) { + const set = this.listeners.get(event); + if (!set) return this; + set.delete(handler); + if (set.size === 0) this.listeners.delete(event); + return this; + } + + removeAllListeners(event) { + if (event) { + this.listeners.delete(event); + } else { + this.listeners.clear(); + } + return this; + } + + // Deprecated aliases for compatibility + addListener(event, handler) { + return this.on(event, handler); + } + + off(event, handler) { + return this.removeListener(event, handler); + } + } + + function install() { + if (!window.ethereumProvider) { + return false; + } + + if (window.__ETHEREUM_INSTALLED__) { + return true; + } + + let provider; + try { + provider = new EthereumProvider(window.ethereumProvider); + } catch (error) { + console.error('[Ethereum Wrapper] Failed to create EthereumProvider:', error); + return false; + } + + if (!window.ethereum) { + Object.defineProperty(window, 'ethereum', { + value: provider, + writable: false, + configurable: false, + enumerable: true + }); + window.__ETHEREUM_INSTALLED__ = true; + window.dispatchEvent(new Event('ethereum#initialized')); + return true; + } else { + console.warn('[Ethereum Wrapper] window.ethereum already present; skipping install'); + return false; + } + } + + function tryInstall() { + if (install()) { + return; + } + + let attempts = 0; + const maxAttempts = 20; + const retryInterval = 50; + + const retry = () => { + attempts++; + if (install()) { + return; + } + + if (attempts < maxAttempts) { + setTimeout(retry, retryInterval * Math.min(attempts, 5)); + } else { + console.error('[Ethereum Wrapper] Failed to install after', maxAttempts, 'attempts'); + } + }; + + setTimeout(retry, retryInterval); + } + + // Return public API if needed + const instance = { + EthereumProvider: EthereumProvider, + install: install, + tryInstall: tryInstall + }; + + // Store instance globally to prevent duplicate loading + window.__ETHEREUM_WRAPPER_INSTANCE__ = instance; + + return instance; + +})(); // IIFE end + +// Auto-install on script load (only if this is the first instance) +if (!window.__ETHEREUM_AUTO_INSTALL_CALLED__) { + window.__ETHEREUM_AUTO_INSTALL_CALLED__ = true; + EthereumWrapper.tryInstall(); +} + + diff --git a/ui/app/AppLayouts/Browser/provider/js/qwebchannel.js b/ui/app/AppLayouts/Browser/provider/js/qwebchannel.js new file mode 100644 index 00000000000..56fa66a65c7 --- /dev/null +++ b/ui/app/AppLayouts/Browser/provider/js/qwebchannel.js @@ -0,0 +1,455 @@ +// Copyright (C) 2016 The Qt Company Ltd. +// Copyright (C) 2016 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com, author Milian Wolff +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +"use strict"; + +var QWebChannelMessageTypes = { + signal: 1, + propertyUpdate: 2, + init: 3, + idle: 4, + debug: 5, + invokeMethod: 6, + connectToSignal: 7, + disconnectFromSignal: 8, + setProperty: 9, + response: 10, +}; + +var QWebChannel = function(transport, initCallback, converters) +{ + if (typeof transport !== "object" || typeof transport.send !== "function") { + console.error("The QWebChannel expects a transport object with a send function and onmessage callback property." + + " Given is: transport: " + typeof(transport) + ", transport.send: " + typeof(transport.send)); + return; + } + + var channel = this; + this.transport = transport; + + var converterRegistry = + { + Date : function(response) { + if (typeof response === "string" + && response.match( + /^-?\d+-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d*)?([-+\u2212](\d{2}):(\d{2})|Z)?$/)) { + var date = new Date(response); + if (!isNaN(date)) + return date; + } + return undefined; // Return undefined if current converter is not applicable + } + }; + + this.usedConverters = []; + + this.addConverter = function(converter) + { + if (typeof converter === "string") { + if (converterRegistry.hasOwnProperty(converter)) + this.usedConverters.push(converterRegistry[converter]); + else + console.error("Converter '" + converter + "' not found"); + } else if (typeof converter === "function") { + this.usedConverters.push(converter); + } else { + console.error("Invalid converter object type " + typeof converter); + } + } + + if (Array.isArray(converters)) { + for (const converter of converters) + this.addConverter(converter); + } else if (converters !== undefined) { + this.addConverter(converters); + } + + this.send = function(data) + { + if (typeof(data) !== "string") { + data = JSON.stringify(data); + } + channel.transport.send(data); + } + + this.transport.onmessage = function(message) + { + var data = message.data; + if (typeof data === "string") { + data = JSON.parse(data); + } + switch (data.type) { + case QWebChannelMessageTypes.signal: + channel.handleSignal(data); + break; + case QWebChannelMessageTypes.response: + channel.handleResponse(data); + break; + case QWebChannelMessageTypes.propertyUpdate: + channel.handlePropertyUpdate(data); + break; + default: + console.error("invalid message received:", message.data); + break; + } + } + + this.execCallbacks = {}; + this.execId = 0; + this.exec = function(data, callback) + { + if (!callback) { + // if no callback is given, send directly + channel.send(data); + return; + } + if (channel.execId === Number.MAX_VALUE) { + // wrap + channel.execId = Number.MIN_VALUE; + } + if (data.hasOwnProperty("id")) { + console.error("Cannot exec message with property id: " + JSON.stringify(data)); + return; + } + data.id = channel.execId++; + channel.execCallbacks[data.id] = callback; + channel.send(data); + }; + + this.objects = {}; + + this.handleSignal = function(message) + { + var object = channel.objects[message.object]; + if (object) { + object.signalEmitted(message.signal, message.args); + } else { + console.warn("Unhandled signal: " + message.object + "::" + message.signal); + } + } + + this.handleResponse = function(message) + { + if (!message.hasOwnProperty("id")) { + console.error("Invalid response message received: ", JSON.stringify(message)); + return; + } + channel.execCallbacks[message.id](message.data); + delete channel.execCallbacks[message.id]; + } + + this.handlePropertyUpdate = function(message) + { + message.data.forEach(data => { + var object = channel.objects[data.object]; + if (object) { + object.propertyUpdate(data.signals, data.properties); + } else { + console.warn("Unhandled property update: " + data.object + "::" + data.signal); + } + }); + channel.exec({type: QWebChannelMessageTypes.idle}); + } + + this.debug = function(message) + { + channel.send({type: QWebChannelMessageTypes.debug, data: message}); + }; + + channel.exec({type: QWebChannelMessageTypes.init}, function(data) { + for (const objectName of Object.keys(data)) { + new QObject(objectName, data[objectName], channel); + } + + // now unwrap properties, which might reference other registered objects + for (const objectName of Object.keys(channel.objects)) { + channel.objects[objectName].unwrapProperties(); + } + + if (initCallback) { + initCallback(channel); + } + channel.exec({type: QWebChannelMessageTypes.idle}); + }); +}; + +function QObject(name, data, webChannel) +{ + this.__id__ = name; + webChannel.objects[name] = this; + + // List of callbacks that get invoked upon signal emission + this.__objectSignals__ = {}; + + // Cache of all properties, updated when a notify signal is emitted + this.__propertyCache__ = {}; + + var object = this; + + // ---------------------------------------------------------------------- + + this.unwrapQObject = function(response) + { + for (const converter of webChannel.usedConverters) { + var result = converter(response); + if (result !== undefined) + return result; + } + + if (response instanceof Array) { + // support list of objects + return response.map(qobj => object.unwrapQObject(qobj)) + } + if (!(response instanceof Object)) + return response; + + if (!response["__QObject*__"] || response.id === undefined) { + var jObj = {}; + for (const propName of Object.keys(response)) { + jObj[propName] = object.unwrapQObject(response[propName]); + } + return jObj; + } + + var objectId = response.id; + if (webChannel.objects[objectId]) + return webChannel.objects[objectId]; + + if (!response.data) { + console.error("Cannot unwrap unknown QObject " + objectId + " without data."); + return; + } + + var qObject = new QObject( objectId, response.data, webChannel ); + qObject.destroyed.connect(function() { + if (webChannel.objects[objectId] === qObject) { + delete webChannel.objects[objectId]; + // reset the now deleted QObject to an empty {} object + // just assigning {} though would not have the desired effect, but the + // below also ensures all external references will see the empty map + // NOTE: this detour is necessary to workaround QTBUG-40021 + Object.keys(qObject).forEach(name => delete qObject[name]); + } + }); + // here we are already initialized, and thus must directly unwrap the properties + qObject.unwrapProperties(); + return qObject; + } + + this.unwrapProperties = function() + { + for (const propertyIdx of Object.keys(object.__propertyCache__)) { + object.__propertyCache__[propertyIdx] = object.unwrapQObject(object.__propertyCache__[propertyIdx]); + } + } + + function addSignal(signalData, isPropertyNotifySignal) + { + var signalName = signalData[0]; + var signalIndex = signalData[1]; + object[signalName] = { + connect: function(callback) { + if (typeof(callback) !== "function") { + console.error("Bad callback given to connect to signal " + signalName); + return; + } + + object.__objectSignals__[signalIndex] = object.__objectSignals__[signalIndex] || []; + object.__objectSignals__[signalIndex].push(callback); + + // only required for "pure" signals, handled separately for properties in propertyUpdate + if (isPropertyNotifySignal) + return; + + // also note that we always get notified about the destroyed signal + if (signalName === "destroyed" || signalName === "destroyed()" || signalName === "destroyed(QObject*)") + return; + + // and otherwise we only need to be connected only once + if (object.__objectSignals__[signalIndex].length == 1) { + webChannel.exec({ + type: QWebChannelMessageTypes.connectToSignal, + object: object.__id__, + signal: signalIndex + }); + } + }, + disconnect: function(callback) { + if (typeof(callback) !== "function") { + console.error("Bad callback given to disconnect from signal " + signalName); + return; + } + // This makes a new list. This is important because it won't interfere with + // signal processing if a disconnection happens while emittig a signal + object.__objectSignals__[signalIndex] = (object.__objectSignals__[signalIndex] || []).filter(function(c) { + return c != callback; + }); + if (!isPropertyNotifySignal && object.__objectSignals__[signalIndex].length === 0) { + // only required for "pure" signals, handled separately for properties in propertyUpdate + webChannel.exec({ + type: QWebChannelMessageTypes.disconnectFromSignal, + object: object.__id__, + signal: signalIndex + }); + } + } + }; + } + + /** + * Invokes all callbacks for the given signalname. Also works for property notify callbacks. + */ + function invokeSignalCallbacks(signalName, signalArgs) + { + var connections = object.__objectSignals__[signalName]; + if (connections) { + connections.forEach(function(callback) { + callback.apply(callback, signalArgs); + }); + } + } + + this.propertyUpdate = function(signals, propertyMap) + { + // update property cache + for (const propertyIndex of Object.keys(propertyMap)) { + var propertyValue = propertyMap[propertyIndex]; + object.__propertyCache__[propertyIndex] = this.unwrapQObject(propertyValue); + } + + for (const signalName of Object.keys(signals)) { + // Invoke all callbacks, as signalEmitted() does not. This ensures the + // property cache is updated before the callbacks are invoked. + invokeSignalCallbacks(signalName, signals[signalName]); + } + } + + this.signalEmitted = function(signalName, signalArgs) + { + invokeSignalCallbacks(signalName, this.unwrapQObject(signalArgs)); + } + + function addMethod(methodData) + { + var methodName = methodData[0]; + var methodIdx = methodData[1]; + + // Fully specified methods are invoked by id, others by name for host-side overload resolution + var invokedMethod = methodName[methodName.length - 1] === ')' ? methodIdx : methodName + + object[methodName] = function() { + var args = []; + var callback; + var errCallback; + for (var i = 0; i < arguments.length; ++i) { + var argument = arguments[i]; + if (typeof argument === "function") + callback = argument; + else + args.push(argument); + } + + var result; + // during test, webChannel.exec synchronously calls the callback + // therefore, the promise must be constucted before calling + // webChannel.exec to ensure the callback is set up + if (!callback && (typeof(Promise) === 'function')) { + result = new Promise(function(resolve, reject) { + callback = resolve; + errCallback = reject; + }); + } + + webChannel.exec({ + "type": QWebChannelMessageTypes.invokeMethod, + "object": object.__id__, + "method": invokedMethod, + "args": args + }, function(response) { + if (response !== undefined) { + var result = object.unwrapQObject(response); + if (callback) { + (callback)(result); + } + } else if (errCallback) { + (errCallback)(); + } + }); + + return result; + }; + } + + function bindGetterSetter(propertyInfo) + { + var propertyIndex = propertyInfo[0]; + var propertyName = propertyInfo[1]; + var notifySignalData = propertyInfo[2]; + // initialize property cache with current value + // NOTE: if this is an object, it is not directly unwrapped as it might + // reference other QObject that we do not know yet + object.__propertyCache__[propertyIndex] = propertyInfo[3]; + + if (notifySignalData) { + if (notifySignalData[0] === 1) { + // signal name is optimized away, reconstruct the actual name + notifySignalData[0] = propertyName + "Changed"; + } + addSignal(notifySignalData, true); + } + + Object.defineProperty(object, propertyName, { + configurable: true, + get: function () { + var propertyValue = object.__propertyCache__[propertyIndex]; + if (propertyValue === undefined) { + // This shouldn't happen + console.warn("Undefined value in property cache for property \"" + propertyName + "\" in object " + object.__id__); + } + + return propertyValue; + }, + set: function(value) { + if (value === undefined) { + console.warn("Property setter for " + propertyName + " called with undefined value!"); + return; + } + object.__propertyCache__[propertyIndex] = value; + var valueToSend = value; + webChannel.exec({ + "type": QWebChannelMessageTypes.setProperty, + "object": object.__id__, + "property": propertyIndex, + "value": valueToSend + }); + } + }); + + } + + // ---------------------------------------------------------------------- + + data.methods.forEach(addMethod); + + data.properties.forEach(bindGetterSetter); + + data.signals.forEach(function(signal) { addSignal(signal, false); }); + + Object.assign(object, data.enums); +} + +QObject.prototype.toJSON = function() { + if (this.__id__ === undefined) return {}; + return { + id: this.__id__, + "__QObject*__": true + }; +}; + +//required for use with nodejs +if (typeof module === 'object') { + module.exports = { + QWebChannel: QWebChannel + }; +} diff --git a/ui/app/AppLayouts/Browser/provider/qml/ConnectorBridge.qml b/ui/app/AppLayouts/Browser/provider/qml/ConnectorBridge.qml new file mode 100644 index 00000000000..e9fffe3fa70 --- /dev/null +++ b/ui/app/AppLayouts/Browser/provider/qml/ConnectorBridge.qml @@ -0,0 +1,135 @@ +import QtQuick +import QtWebEngine +import QtWebChannel + +import "Utils.js" as BrowserUtils + +/** + * ConnectorBridge + * + * Simplified connector infrastructure for BrowserLayout. + * Provides WebEngine profiles with script injection, WebChannel, + * ConnectorManager, and direct connection to Nim backend. + * + * This component bridges the Browser UI with the Connector backend system. + */ +QtObject { + id: root + + required property string userUID + required property var connectorController + property string httpUserAgent: "" // Custom user agent for web profiles + + readonly property alias webChannel: channel + readonly property alias manager: connectorManager + + property alias dappUrl: connectorManager.dappUrl + property alias dappOrigin: connectorManager.dappOrigin + property alias dappName: connectorManager.dappName + property alias dappIconUrl: connectorManager.dappIconUrl + property alias clientId: connectorManager.clientId + + function hasWalletConnected(hostname, address) { + if (!connectorController) return false + + const dApps = connectorController.getDApps() + try { + const dAppsObj = JSON.parse(dApps) + if (Array.isArray(dAppsObj)) { + return dAppsObj.some(function(dapp) { + return dapp.url && dapp.url.indexOf(hostname) >= 0 + }) + } + } catch (e) { + console.warn("[ConnectorBridge] Error checking wallet connection:", e) + } + return false + } + + function disconnect(hostname) { + if (!connectorController) return false + return connectorController.disconnect(hostname) + } + + function updateDAppUrl(url, name) { + if (!url) return + + const urlStr = url.toString() + connectorManager.dappUrl = urlStr + connectorManager.dappOrigin = urlStr + connectorManager.dappName = name || BrowserUtils.extractDomainName(urlStr) + connectorManager.dappChainId = 1 + } + + function createScript(scriptName, runOnSubframes = true) { + return { + name: scriptName, + sourceUrl: Qt.resolvedUrl("../js/" + scriptName), + injectionPoint: WebEngineScript.DocumentCreation, + worldId: WebEngineScript.MainWorld, + runOnSubframes: runOnSubframes + } + } + + readonly property var _scripts: [ + createScript("qwebchannel.js", true), + createScript("ethereum_wrapper.js", true), + createScript("eip6963_announcer.js", false), // Only top-level window (EIP-6963 spec) + createScript("ethereum_injector.js", true) + ] + + readonly property WebEngineProfile defaultProfile: WebEngineProfile { + storageName: "Profile_%1".arg(root.userUID) + offTheRecord: false + httpUserAgent: root.httpUserAgent + userScripts.collection: root._scripts + } + + readonly property WebEngineProfile otrProfile: WebEngineProfile { + storageName: "IncognitoProfile_%1".arg(root.userUID) + offTheRecord: true + persistentCookiesPolicy: WebEngineProfile.NoPersistentCookies + httpUserAgent: root.httpUserAgent + userScripts.collection: root._scripts + } + + readonly property ConnectorManager connectorManager: ConnectorManager { + connectorController: root.connectorController // (shared_modules/connector/controller.nim) + + dappUrl: "" + dappOrigin: "" + dappName: "" + dappIconUrl: "" + dappChainId: 1 + clientId: "status-desktop/dapp-browser" + + // Forward events to Eip1193ProviderAdapter + onConnectEvent: (info) => eip1193ProviderAdapter.connectEvent(info) + onAccountsChangedEvent: (accounts) => eip1193ProviderAdapter.accountsChangedEvent(accounts) + onChainChangedEvent: (chainId) => eip1193ProviderAdapter.chainChangedEvent(chainId) + onRequestCompletedEvent: (payload) => eip1193ProviderAdapter.requestCompletedEvent(payload) + onDisconnectEvent: (error) => eip1193ProviderAdapter.disconnectEvent(error) + onMessageEvent: (message) => eip1193ProviderAdapter.messageEvent(message) + + onProviderStateChanged: () => eip1193ProviderAdapter.providerStateChanged() + } + + readonly property WebChannel channel: WebChannel { + registeredObjects: [eip1193ProviderAdapter] + } + + readonly property Eip1193ProviderAdapter eip1193ProviderAdapter: Eip1193ProviderAdapter { + WebChannel.id: "ethereumProvider" + + chainId: BrowserUtils.chainIdToHex(connectorManager.dappChainId) + networkVersion: connectorManager.dappChainId.toString() + selectedAddress: connectorManager.accounts.length > 0 ? connectorManager.accounts[0] : "" + accounts: connectorManager.accounts + connected: connectorManager.connected + + function request(args) { + return connectorManager.request(args) + } + } +} + diff --git a/ui/app/AppLayouts/Browser/provider/qml/ConnectorManager.qml b/ui/app/AppLayouts/Browser/provider/qml/ConnectorManager.qml new file mode 100644 index 00000000000..9d042c85a2b --- /dev/null +++ b/ui/app/AppLayouts/Browser/provider/qml/ConnectorManager.qml @@ -0,0 +1,229 @@ +import QtQuick +import "Utils.js" as Utils + +QtObject { + id: root + + property var connectorController: null + + // dApp metadata + required property string dappUrl + required property string dappOrigin + required property string dappName + required property string dappIconUrl + required property int dappChainId + required property string clientId + + // STATE + property bool connected: false + property var accounts: [] + property bool _initialConnectionDone: false + + // SIGNALS + // Notify to re-read all properties + signal providerStateChanged() + + // events for Eip1193ProviderAdapter + signal connectEvent(var info) + signal disconnectEvent(var error) + signal accountsChangedEvent(var accounts) + signal chainChangedEvent(string chainId) + signal messageEvent(var message) + signal requestCompletedEvent(var payload) + + // PUBLIC API - EIP-1193 REQUEST + function request(args) { + if (!args || !args.method) { + console.error("[ConnectorManager] Invalid request") + return JSON.stringify({ + error: { code: -32600, message: "Missing method" } + }) + } + + const method = args.method + const requestId = args.requestId || 0 + + var rpcRequest = { + "jsonrpc": "2.0", + "id": requestId, + "method": method, + "params": args.params || [], + "url": dappOrigin || dappUrl || "", + "name": dappName || "Unknown dApp", + "clientId": clientId, + "chainId": dappChainId, + "iconUrl": dappIconUrl || "" + } + + // Direct call to Nim connectorCallRPC -> status-go connector/api.go + if (!connectorController) { + console.error("[ConnectorManager] connectorController not available") + return JSON.stringify({ + jsonrpc: "2.0", + id: requestId, + error: { code: -32603, message: "Internal error: connector not available" } + }) + } + + connectorController.connectorCallRPC(requestId, JSON.stringify(rpcRequest)) + + // Return immediately - response comes via connectorCallRPCResult signal + return JSON.stringify({ + jsonrpc: "2.0", + id: requestId, + result: null + }) + } + + // STATE MANAGEMENT METHODS + function updateAccounts(newAccounts) { + if (!Utils.accountsDidChange(accounts, newAccounts)) { + return false + } + + accounts = newAccounts + + providerStateChanged() + accountsChangedEvent(accounts) + console.log("[ConnectorManager] Accounts updated:", JSON.stringify(accounts)) + return true + } + + function setConnected(isConnected) { + if (connected === isConnected) { + return false + } + + connected = isConnected + + if (connected && !_initialConnectionDone) { + _initialConnectionDone = true + const chainIdHex = Utils.chainIdToHex(dappChainId) + + providerStateChanged() + connectEvent({ chainId: chainIdHex }) + console.log("[ConnectorManager] Initial connection established") + } else { + providerStateChanged() + } + + return true + } + + function clearState() { + if (accounts.length === 0 && !connected) { + return false + } + + accounts = [] + connected = false + _initialConnectionDone = false + + providerStateChanged() + disconnectEvent({ code: 4900, message: "User disconnected" }) // EIP-1193: Disconnected + accountsChangedEvent([]) + console.log("[ConnectorManager] State cleared") + return true + } + + // PUBLIC API + function disconnect() { + console.log("[ConnectorManager] Disconnecting dApp") + + clearState() + + if (connectorController) { + const effectiveUrl = dappOrigin || dappUrl + console.log("[ConnectorManager] Calling backend disconnect for:", effectiveUrl) + connectorController.disconnect(effectiveUrl) + } + } + + // HELPER FUNCTIONS + function shouldProcessSignal(event) { + // Filter by origin + if (event.url && Utils.normalizeOrigin(event.url) !== Utils.normalizeOrigin(dappOrigin)) { + console.log("[ConnectorManager] Ignoring signal for other origin:", event.url, "expected:", dappOrigin) + return false + } + + // Filter by clientId + if (event.clientId !== undefined && event.clientId !== "" && clientId !== "" && event.clientId !== clientId) { + console.log("[ConnectorManager] Ignoring signal for other clientId:", event.clientId, "expected:", clientId) + return false + } + + return true + } + + // SIGNAL HANDLERS + Connections { + target: connectorController + + function onConnected(payload) { + try { + const data = JSON.parse(payload) + + if (!shouldProcessSignal(data)) return + + const newAccounts = data.sharedAccount ? [data.sharedAccount] : [] + updateAccounts(newAccounts) + + if (data.chainId) { + const newChainId = data.chainId + if (dappChainId !== newChainId) { + dappChainId = newChainId + const chainIdHex = Utils.chainIdToHex(newChainId) + + providerStateChanged() + chainChangedEvent(chainIdHex) + console.log("[ConnectorManager] Chain updated:", chainIdHex) + } + } + + setConnected(true) + } catch (error) { + console.error("[ConnectorManager] Error processing connected signal:", error) + } + } + + function onDisconnected(payload) { + try { + const data = JSON.parse(payload) + if (!shouldProcessSignal(data)) return + clearState() + } catch (error) { + console.error("[ConnectorManager] Error processing disconnected signal:", error) + } + } + + function onConnectorCallRPCResult(requestId, payload) { + // Emit to Eip1193ProviderAdapter → ethereum_wrapper.js + requestCompletedEvent({ + requestId: requestId, + response: payload + }) + } + + function onChainIdSwitched(payload) { + try { + const data = JSON.parse(payload) + + if (!shouldProcessSignal(data)) return + + const chainIdDecimal = Utils.parseChainId(data.chainId) + + if (dappChainId !== chainIdDecimal) { + dappChainId = chainIdDecimal + const chainIdHex = Utils.chainIdToHex(chainIdDecimal) + + providerStateChanged() + chainChangedEvent(chainIdHex) + console.log("[ConnectorManager] Chain switched to:", chainIdHex) + } + } catch (error) { + console.error("[ConnectorManager] Error processing chainIdSwitched signal:", error) + } + } + } +} diff --git a/ui/app/AppLayouts/Browser/provider/qml/Eip1193ProviderAdapter.qml b/ui/app/AppLayouts/Browser/provider/qml/Eip1193ProviderAdapter.qml new file mode 100644 index 00000000000..dca3ff33967 --- /dev/null +++ b/ui/app/AppLayouts/Browser/provider/qml/Eip1193ProviderAdapter.qml @@ -0,0 +1,42 @@ +import QtQuick + +QtObject { + id: root + + // ============================================================================ + // EIP-1193 PUBLIC PROPERTIES (exposed to JS via WebChannel) + // ============================================================================ + readonly property bool isStatus: true + readonly property bool isMetaMask: false + property string chainId: "0x1" // hex format for EIP-1193 + property string networkVersion: "1" // decimal format (deprecated but used by some dApps) + property string selectedAddress: "" // current active address + property var accounts: [] + property bool connected: false + + // ============================================================================ + // EIP-1193 EVENTS (for WebChannel) + // ============================================================================ + + signal connectEvent(var info) + signal disconnectEvent(var error) + signal accountsChangedEvent(var accounts) + signal chainChangedEvent(string chainId) + signal messageEvent(var message) + signal requestCompletedEvent(var payload) + + // Internal + signal providerStateChanged() // re-read State + + // ============================================================================ + // EIP-1193 REQUEST METHOD STUB + // ============================================================================ + function request(args) { + console.error("[Eip1193ProviderAdapter] request() not injected - should be overridden by ConnectorBridge") + return JSON.stringify({ + jsonrpc: "2.0", + id: args && args.requestId || 0, + error: { code: -32603, message: "Request function not properly injected" } + }) + } +} diff --git a/ui/app/AppLayouts/Browser/provider/qml/Utils.js b/ui/app/AppLayouts/Browser/provider/qml/Utils.js new file mode 100644 index 00000000000..a1332c229c0 --- /dev/null +++ b/ui/app/AppLayouts/Browser/provider/qml/Utils.js @@ -0,0 +1,55 @@ +function accountsDidChange(oldAccounts, newAccounts) { + const a = oldAccounts || [] + const b = newAccounts || [] + + if (a.length !== b.length) return true + + const setA = new Set(a.map(addr => addr.toLowerCase())) + const setB = new Set(b.map(addr => addr.toLowerCase())) + + return setA.size !== setB.size || ![...setA].every(addr => setB.has(addr)) +} + +function normalizeOrigin(url) { + if (!url) return "" + let normalized = url.toString() + // Remove trailing slash from origin + if (normalized.endsWith("/")) { + normalized = normalized.slice(0, -1) + } + return normalized +} + +// Convert decimal chainId to hex string (e.g., 1 -> "0x1", 137 -> "0x89") +function chainIdToHex(chainIdDecimal) { + if (typeof chainIdDecimal !== "number" || chainIdDecimal < 0) { + console.error("[Utils] Invalid chainId:", chainIdDecimal) + return "0x1" // Default to Mainnet + } + return "0x" + chainIdDecimal.toString(16) +} + +// Parse chainId from any format (hex string or decimal) to decimal number +function parseChainId(chainId) { + if (typeof chainId === "number") { + return chainId + } + if (typeof chainId === "string") { + if (chainId.startsWith("0x")) { + return parseInt(chainId, 16) + } + return parseInt(chainId, 10) + } + return 1 // Default to Mainnet +} + +// Extract domain name from URL string +function extractDomainName(urlString) { + try { + const urlObj = new URL(urlString) + return urlObj.hostname || "Unknown dApp" + } catch (e) { + return "Unknown dApp" + } +} + diff --git a/ui/app/AppLayouts/Wallet/services/dapps/BCDappsProvider.qml b/ui/app/AppLayouts/Wallet/services/dapps/BCDappsProvider.qml index 5d3b19e947e..af4f656d082 100644 --- a/ui/app/AppLayouts/Wallet/services/dapps/BCDappsProvider.qml +++ b/ui/app/AppLayouts/Wallet/services/dapps/BCDappsProvider.qml @@ -1,9 +1,6 @@ import QtQuick import AppLayouts.Wallet.services.dapps -import StatusQ.Core.Utils - -import shared.stores import utils DAppsModel {