Skip to content
Merged
Show file tree
Hide file tree
Changes from 14 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
dist
node_modules
*.tsbuildinfo
.claude
Binary file modified .yarn/install-state.gz
Binary file not shown.
8 changes: 5 additions & 3 deletions manifest/base.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,19 +28,21 @@
"48": "icons/ethui-black-48.png",
"96": "icons/ethui-black-96.png",
"128": "icons/ethui-black-128.png"
}
},
"default_popup": "popup/index.html"
},
"web_accessible_resources": [
{
"matches": ["<all_urls>"],
"resources": [
"/inpage/inpage.js",
"devtools/index.html",
"panel/index.html"
"panel/index.html",
"popup/index.html"
]
}
],
"permissions": ["storage"],
"permissions": ["storage", "notifications"],
"icons": {
"16": "icons/ethui-black-16.png",
"48": "icons/ethui-black-48.png",
Expand Down
5 changes: 5 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@
"dependencies": {
"@devtools-ds/object-inspector": "^1.2.1",
"@devtools-ds/table": "^1.2.1",
"@ethui/ui": "^0.0.141",
"@fontsource/source-code-pro": "^5.2.5",
"@lukeed/uuid": "^2.0.1",
"@metamask/eth-json-rpc-middleware": "^23.0.0",
"@metamask/json-rpc-engine": "^10.2.0",
Expand All @@ -35,12 +37,15 @@
"react": "^19.2.0",
"react-dom": "^19.2.0",
"stream": "^0.0.3",
"tailwindcss": "^4.1.5",
"viem": "^2.44.4",
"webextension-polyfill": "^0.12.0",
"websocket-ts": "^2.2.1",
"zustand": "^5.0.5"
},
"devDependencies": {
"@biomejs/biome": "^2.3.1",
"@tailwindcss/vite": "^4.1.5",
"@types/chrome": "^0.1.0",
"@types/json-merge-patch": "^1.0.0",
"@types/node": "^22.14.0",
Expand Down
234 changes: 234 additions & 0 deletions src/background/connectionState.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,234 @@
/// <reference types="chrome" />
import { action, runtime } from "webextension-polyfill";

import { loadSettings } from "#/settings";

export type ConnectionState = "connected" | "disconnected" | "unknown";

export interface WalletInfo {
accounts: string[];
chainId: string;
balance: string;
}

let globalConnectionState: ConnectionState = "unknown";
let hasShownNotification = false;

const NOTIFICATION_ID = "ethui-connection-status";

export function getConnectionState(): ConnectionState {
return globalConnectionState;
}

export function setConnectionState(state: ConnectionState) {
const previousState = globalConnectionState;
globalConnectionState = state;

// Broadcast state change to any open popups
runtime
.sendMessage({
type: "connection-state",
state: globalConnectionState,
})
.catch(() => {
// Popup may not be open, ignore error
});

updateBadge();

// Show notification on first disconnection
if (
state === "disconnected" &&
previousState !== "disconnected" &&
!hasShownNotification
) {
showDisconnectedNotification();
hasShownNotification = true;
}

// Reset notification flag when connected
if (state === "connected") {
hasShownNotification = false;
}
}

function updateBadge() {
if (globalConnectionState === "disconnected") {
action.setBadgeText({ text: "!" });
action.setBadgeBackgroundColor({ color: "#ef4444" });
} else if (globalConnectionState === "connected") {
Comment thread
naps62 marked this conversation as resolved.
Outdated
action.setBadgeText({ text: "" });
}
}

function showDisconnectedNotification() {
if (!chrome.notifications?.create) {
return;
}

chrome.notifications.create(NOTIFICATION_ID, {
type: "basic",
iconUrl: chrome.runtime.getURL("icons/ethui-black-128.png"),
title: "ethui Desktop Not Running",
message:
"The ethui desktop app doesn't appear to be running. Click the extension icon for more info.",
});
}
Comment thread
naps62 marked this conversation as resolved.
Outdated

async function checkConnection(): Promise<ConnectionState> {
const settings = await loadSettings();
const endpoint = settings.endpoint;

return new Promise((resolve) => {
let resolved = false;
const done = (state: ConnectionState) => {
if (resolved) return;
resolved = true;
clearTimeout(timeout);
setConnectionState(state);
resolve(state);
};

const ws = new WebSocket(endpoint);
const timeout = setTimeout(() => {
ws.close();
done("disconnected");
}, 3000);

ws.onopen = () => {
ws.close();
done("connected");
Comment thread
naps62 marked this conversation as resolved.
};

ws.onerror = () => {
ws.close();
done("disconnected");
};

ws.onclose = () => {
done("disconnected");
};
Comment thread
naps62 marked this conversation as resolved.
});
}

async function fetchWalletInfo(): Promise<WalletInfo | null> {
const settings = await loadSettings();
const endpoint = settings.endpoint;

return new Promise((resolve) => {
const ws = new WebSocket(endpoint);
let requestId = 1;
const pending = new Map<number, (result: unknown) => void>();

const sendRequest = (method: string, params: unknown[] = []) => {
const id = requestId++;
return new Promise<unknown>((res) => {
pending.set(id, res);
ws.send(JSON.stringify({ jsonrpc: "2.0", id, method, params }));
});
};

const timeout = setTimeout(() => {
ws.close();
resolve(null);
}, 5000);

ws.onopen = async () => {
try {
const [accounts, chainId] = await Promise.all([
sendRequest("eth_accounts"),
sendRequest("eth_chainId"),
]);

const accountsArray = accounts as string[];
let balance = "0x0";

if (accountsArray.length > 0) {
balance = (await sendRequest("eth_getBalance", [
accountsArray[0],
"latest",
])) as string;
}

clearTimeout(timeout);
ws.close();
resolve({
accounts: accountsArray,
chainId: chainId as string,
balance,
});
} catch {
clearTimeout(timeout);
ws.close();
resolve(null);
}
};

ws.onmessage = (event) => {
try {
const data = JSON.parse(event.data);
if (data.id && pending.has(data.id)) {
const callback = pending.get(data.id)!;
pending.delete(data.id);
callback(data.result);
}
} catch {
// Ignore parse errors
}
};

ws.onerror = () => {
clearTimeout(timeout);
resolve(null);
};

ws.onclose = () => {
clearTimeout(timeout);
};
});
Comment thread
naps62 marked this conversation as resolved.
}

export function setupConnectionStateListener() {
runtime.onMessage.addListener((message: unknown) => {
if (typeof message !== "object" || message === null || !("type" in message)) {
return;
}

const msg = message as { type: string };

if (msg.type === "get-connection-state") {
// If state is unknown, check connection before responding
if (globalConnectionState === "unknown") {
return checkConnection().then((state) => ({
type: "connection-state",
state,
}));
}
return Promise.resolve({
type: "connection-state",
state: globalConnectionState,
});
}

if (msg.type === "get-wallet-info") {
return fetchWalletInfo().then((info) => ({
type: "wallet-info",
info,
}));
}

if (msg.type === "check-connection") {
return checkConnection().then((state) => ({
type: "connection-state",
state,
}));
}
});
Comment thread
naps62 marked this conversation as resolved.
Outdated

// Handle notification click - open ethui.dev
chrome.notifications.onClicked.addListener((notificationId) => {
if (notificationId === NOTIFICATION_ID) {
chrome.tabs.create({ url: "https://ethui.dev" });
}
});
}
13 changes: 8 additions & 5 deletions src/background/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import log from "loglevel";
import { action, type Runtime, runtime } from "webextension-polyfill";
import { type Runtime, runtime } from "webextension-polyfill";
import { ArrayQueue, ConstantBackoff, WebsocketBuilder } from "websocket-ts";

import { defaultSettings, loadSettings, type Settings } from "#/settings";
import { setConnectionState, setupConnectionStateListener } from "./connectionState";
import { startHeartbeat } from "./heartbeat";

// init on load
Expand All @@ -18,6 +19,8 @@ async function init() {
settings = await loadSettings();
log.setLevel(settings.logLevel);

setupConnectionStateListener();

// handle each incoming content script connection
runtime.onConnect.addListener((port: Runtime.Port) => {
if (!port.sender) {
Expand All @@ -30,10 +33,6 @@ async function init() {

setupProviderConnection(port);
});

action.onClicked.addListener(() => {
console.log("icon clicked");
});
}

/**
Expand Down Expand Up @@ -97,6 +96,7 @@ function setupProviderConnection(port: Runtime.Port) {
.onOpen(() => {
log.debug(`WS connection opened (${url})`);
isConnecting = false;
setConnectionState("connected");

// flush queue
while (queue.length > 0) {
Expand All @@ -108,13 +108,16 @@ function setupProviderConnection(port: Runtime.Port) {
log.debug(`WS connection closed (${url})`);
ws = undefined;
isConnecting = false;
setConnectionState("disconnected");
})
.onReconnect(() => {
log.debug("WS connection reconnected");
setConnectionState("connected");
})
.onError((e) => {
log.error("[WS] error:", e);
isConnecting = false;
setConnectionState("disconnected");
})
.withBuffer(new ArrayQueue())
.withBackoff(new ConstantBackoff(1000))
Expand Down
Loading
Loading