Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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.
9 changes: 9 additions & 0 deletions biome.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,15 @@
"formatter": {
"indentStyle": "space"
},
"css": {
"parser": {
"cssModules": true,
"tailwindDirectives": true
},
"linter": {
"enabled": false
}
},
"linter": {
"rules": {
"recommended": true,
Expand Down
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
256 changes: 256 additions & 0 deletions src/background/connectionState.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,256 @@
import { action, notifications, runtime, tabs } from "webextension-polyfill";

import { loadSettings } from "#/settings";

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

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

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

const NOTIFICATION_ID = "ethui-connection-status";

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 {
action.setBadgeText({ text: "" });
}
}

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

notifications.create(NOTIFICATION_ID, {
type: "basic",
iconUrl: 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.",
});
}

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 = () => {
done("connected");
Comment thread
naps62 marked this conversation as resolved.
ws.close();
};

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,
{ resolve: (result: unknown) => void; reject: (err: Error) => void }
>();

const rejectAllPending = (reason: string) => {
const error = new Error(reason);
for (const { reject } of pending.values()) {
reject(error);
}
pending.clear();
};

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

const timeout = setTimeout(() => {
rejectAllPending("Request timed out");
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 { resolve: res } = pending.get(data.id)!;
pending.delete(data.id);
res(data.result);
}
} catch {
// Ignore parse errors
}
};

ws.onerror = () => {
clearTimeout(timeout);
rejectAllPending("WebSocket error");
resolve(null);
};

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

export function setupConnectionStateListener() {
const handleMessage = (
message: unknown,
_sender: unknown,
sendResponse: (r: unknown) => void,
): true | undefined => {
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") {
checkConnection().then((state) => {
sendResponse({ type: "connection-state", state });
});
} else {
sendResponse({
type: "connection-state",
state: globalConnectionState,
});
}
return true;
}

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

if (msg.type === "check-connection") {
checkConnection().then((state) => {
sendResponse({ type: "connection-state", state });
});
return true;
}
};

runtime.onMessage.addListener(
handleMessage as Parameters<typeof runtime.onMessage.addListener>[0],
);

// Handle notification click - open ethui.dev
notifications.onClicked.addListener((notificationId) => {
if (notificationId === NOTIFICATION_ID) {
tabs.create({ url: "https://ethui.dev" });
}
});
}
16 changes: 11 additions & 5 deletions src/background/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
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 +22,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 +36,6 @@ async function init() {

setupProviderConnection(port);
});

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

/**
Expand Down Expand Up @@ -97,6 +99,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 +111,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